# app.py - 修复试卷管理功能
from flask import Flask, request, jsonify, session, render_template_string
from flask_cors import CORS
from datetime import datetime
import json
import os
from services import *
from database import Database

app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
CORS(app)

# 初始化服务
db = Database()
similarity_service = SimilarityCheckService()
difficulty_service = DifficultyAnalysisService()
question_service = QuestionService(db, similarity_service)
paper_service = PaperService(db, difficulty_service)
user_service = UserService(db)
log_service = LogService(db)
enhanced_similarity_service = EnhancedSimilarityService(db)
enhanced_difficulty_service = EnhancedDifficultyAnalysisService(db)


# 权限装饰器
def require_login(f):
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            return jsonify({'error': '请先登录'}), 401
        return f(*args, **kwargs)

    decorated_function.__name__ = f.__name__
    return decorated_function


def require_role(required_roles):
    def decorator(f):
        def decorated_function(*args, **kwargs):
            if 'user_role' not in session or session['user_role'] not in required_roles:
                return jsonify({'error': '权限不足'}), 403
            return f(*args, **kwargs)

        decorated_function.__name__ = f.__name__
        return decorated_function

    return decorator


# 权限检查函数
def check_question_ownership(question_id, user_id, user_role):
    """检查试题所有权"""
    try:
        if user_role == 'admin':
            return True
        question = db.get_question_by_id(question_id)
        if not question:
            return False
        if user_role == 'teacher':
            if not question.creator_id or question.creator_id == user_id:
                return True
            return True
        return False
    except Exception as e:
        print(f"❌权限检查失败: {e}")
        return user_role in ['admin', 'teacher']


def check_paper_ownership(paper_id, user_id, user_role):
    """检查试卷所有权"""
    try:
        if user_role == 'admin':
            return True
        paper = db.get_paper_by_id(paper_id)
        if not paper:
            return False
        if user_role == 'teacher':
            if not paper.creator_id or paper.creator_id == user_id:
                return True
            return True
        return False
    except Exception as e:
        print(f"❌试卷权限检查失败: {e}")
        return user_role in ['admin', 'teacher']


# 用户管理API
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    if data.get('role') == 'admin':
        admin_key = data.get('admin_key')
        if admin_key != '123456':
            return jsonify({'error': '管理员密钥错误'}), 403

    success, message = user_service.create_user(data)
    if success:
        log_service.log_user_action('system', 'user_register', f"新用户注册: {data.get('username')}")
        return jsonify({'message': message}), 201
    else:
        return jsonify({'error': message}), 400


@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    success, user = user_service.authenticate_user(username, password)
    if success:
        session['user_id'] = user.id
        session['user_role'] = user.role.value
        session['username'] = user.username
        log_service.log_user_action(user.id, 'login', '用户登录', request.remote_addr)
        return jsonify({
            'message': '登录成功',
            'user': {
                'id': user.id,
                'username': user.username,
                'role': user.role.value,
                'email': user.email
            }
        })
    else:
        return jsonify({'error': '用户名或密码错误'}), 401


@app.route('/api/logout', methods=['POST'])
@require_login
def logout():
    user_id = session.get('user_id')
    log_service.log_user_action(user_id, 'logout', '用户登出')
    session.clear()
    return jsonify({'message': '登出成功'})


@app.route('/api/user/current', methods=['GET'])
@require_login
def get_current_user():
    return jsonify({
        'user_id': session.get('user_id'),
        'username': session.get('username'),
        'role': session.get('user_role')
    })


@app.route('/api/subjects', methods=['GET'])
@require_login
def get_subjects():
    try:
        subjects = db.get_all_subjects()
        return jsonify({'subjects': subjects})
    except Exception as e:
        return jsonify({'error': '获取学科列表失败'}), 500


# 管理员用户管理API
@app.route('/api/users', methods=['GET'])
@require_login
@require_role(['admin'])
def get_all_users():
    try:
        users = db.get_all_users()
        users_data = []
        for user in users:
            users_data.append({
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'role': user.role.value,
                'created_time': user.created_time.isoformat()
            })
        return jsonify({'users': users_data})
    except Exception as e:
        return jsonify({'error': '获取用户列表失败'}), 500


@app.route('/api/users/<user_id>', methods=['DELETE'])
@require_login
@require_role(['admin'])
def delete_user(user_id):
    try:
        success = db.delete_user(user_id)
        if success:
            log_service.log_user_action(session.get('user_id'), 'delete_user', f"删除用户: {user_id}")
            return jsonify({'message': '用户删除成功'}), 200
        else:
            return jsonify({'error': '用户删除失败'}), 500
    except Exception as e:
        return jsonify({'error': '删除用户时发生错误'}), 500


# 试题管理API
@app.route('/api/questions', methods=['POST'])
@require_login
@require_role(['admin', 'teacher'])
def create_question():
    """创建试题（整合相似度检查和难度分析）"""
    data = request.get_json()
    user_id = session.get('user_id')

    try:
        question_draft = question_service.create_question_draft(data, user_id)
        similarity_result = question_service.check_question_similarity(question_draft)

        if similarity_result['has_similar'] and not data.get('force_create', False):
            max_similarity = 0
            similar_questions_serialized = []
            for similar_data in similarity_result['similar_questions']:
                if isinstance(similar_data, dict):
                    similarity_score = similar_data.get('similarity', 0)
                    question_obj = similar_data.get('question')
                else:
                    similarity_score = getattr(similar_data, 'similarity', 0)
                    question_obj = similar_data

                if similarity_score > max_similarity:
                    max_similarity = similarity_score

                if question_obj:
                    similar_questions_serialized.append({
                        'id': question_obj.id,
                        'content': question_obj.content[:100] + ('...' if len(question_obj.content) > 100 else ''),
                        'difficulty': question_obj.difficulty.value if hasattr(question_obj.difficulty,
                                                                               'value') else int(
                            question_obj.difficulty),
                        'subject': question_obj.subject,
                        'similarity_score': round(similarity_score * 100, 1)
                    })

            return jsonify({
                'error': f'❌试题相似度过高（{round(max_similarity * 100, 1)}%），无法添加',
                'similarity_check': {
                    'has_similar': True,
                    'similar_questions': similar_questions_serialized,
                    'max_similarity': round(max_similarity * 100, 1)
                }
            }), 400

        success = question_service.finalize_question(question_draft)
        if success:
            # 自动进行难度分析
            try:
                difficulty_analysis = enhanced_difficulty_service.analyze_question_difficulty(question_draft)
                log_service.log_user_action(user_id, 'create_question',
                                            f"创建试题: {question_draft.content[:50]}")

                return jsonify({
                    'message': '✅试题创建成功！',
                    'question_id': question_draft.id,
                    'difficulty_analysis': difficulty_analysis
                }), 201
            except Exception as e:
                print(f"难度分析失败: {e}")
                # 即使难度分析失败，试题创建仍然成功
                log_service.log_user_action(user_id, 'create_question',
                                            f"创建试题: {question_draft.content[:50]}")
                return jsonify({
                    'message': '✅试题创建成功！',
                    'question_id': question_draft.id
                }), 201
        else:
            return jsonify({'error': '❌试题创建失败'}), 500

    except Exception as e:
        return jsonify({'error': f'❌创建试题时发生错误: {str(e)}'}), 500


@app.route('/api/questions/search', methods=['GET'])
@require_login
def search_questions():
    filters = {}
    user_role = session.get('user_role')
    user_id = session.get('user_id')

    if request.args.get('subject'):
        filters['subject'] = request.args.get('subject')
    if request.args.get('difficulty'):
        filters['difficulty'] = int(request.args.get('difficulty'))
    if request.args.get('keyword'):
        filters['keyword'] = request.args.get('keyword')

    questions = question_service.search_questions(filters)
    questions_data = []
    for q in questions:
        question_data = {
            'id': q.id,
            'content': q.content,
            'question_type': q.question_type.value,
            'difficulty': q.difficulty.value,
            'subject': q.subject,
            'chapter': q.chapter,
            'answer': q.answer,
            'explanation': q.explanation,
            'tags': q.tags,
            'usage_count': q.usage_count,
            'created_time': q.created_time.isoformat(),
            'can_edit': check_question_ownership(q.id, user_id, user_role),
            'can_delete': check_question_ownership(q.id, user_id, user_role)
        }
        questions_data.append(question_data)

    return jsonify({'questions': questions_data})


@app.route('/api/questions/<question_id>', methods=['GET'])
@require_login
def get_question(question_id):
    try:
        question = db.get_question_by_id(question_id)
        if question:
            user_role = session.get('user_role')
            user_id = session.get('user_id')
            question_data = {
                'id': question.id,
                'content': question.content,
                'question_type': question.question_type.value,
                'difficulty': question.difficulty.value,
                'subject': question.subject,
                'chapter': question.chapter,
                'answer': question.answer,
                'explanation': question.explanation,
                'tags': question.tags,
                'usage_count': question.usage_count,
                'created_time': question.created_time.isoformat(),
                'can_edit': check_question_ownership(question_id, user_id, user_role),
                'can_delete': check_question_ownership(question_id, user_id, user_role)
            }
            return jsonify({'question': question_data})
        else:
            return jsonify({'error': '试题不存在'}), 404
    except Exception as e:
        return jsonify({'error': '获取试题失败'}), 500


@app.route('/api/questions/<question_id>', methods=['PUT'])
@require_login
@require_role(['admin', 'teacher'])
def update_question(question_id):
    data = request.get_json()
    user_id = session.get('user_id')
    user_role = session.get('user_role')

    if not check_question_ownership(question_id, user_id, user_role):
        return jsonify({'error': '您没有权限编辑此试题'}), 403

    try:
        success = db.update_question(question_id, data)
        if success:
            log_service.log_user_action(user_id, 'update_question', f"更新试题: {question_id}")
            return jsonify({'message': '试题更新成功'}), 200
        else:
            return jsonify({'error': '试题更新失败'}), 500
    except Exception as e:
        return jsonify({'error': '更新试题时发生错误'}), 500


@app.route('/api/questions/<question_id>', methods=['DELETE'])
@require_login
@require_role(['admin', 'teacher'])
def delete_question(question_id):
    user_id = session.get('user_id')
    user_role = session.get('user_role')

    if not check_question_ownership(question_id, user_id, user_role):
        return jsonify({'error': '您没有权限删除此试题'}), 403

    try:
        success = db.delete_question(question_id)
        if success:
            log_service.log_user_action(user_id, 'delete_question', f"删除试题: {question_id}")
            return jsonify({'message': '试题删除成功'}), 200
        else:
            return jsonify({'error': '试题删除失败'}), 500
    except Exception as e:
        return jsonify({'error': '删除试题时发生错误'}), 500


# 试卷管理API - 修复和新增功能
@app.route('/api/papers', methods=['POST'])
@require_login
@require_role(['admin', 'teacher'])
def create_paper():
    data = request.get_json()
    user_id = session.get('user_id')

    try:
        if data.get('auto_generate', False):
            paper = paper_service.create_auto_paper(data, user_id)
        else:
            # 手动创建试卷
            paper_data = {
                'title': data.get('name', data.get('title', '')),
                'description': data.get('description', ''),
                'subject': data.get('subject', ''),
                'questions': []
            }

            # 处理试题列表
            if 'question_ids' in data:
                for q_id in data['question_ids']:
                    paper_data['questions'].append({
                        'question_id': q_id,
                        'score': 5
                    })
            elif 'questions' in data:
                paper_data['questions'] = data['questions']

            paper = paper_service.create_manual_paper(paper_data, user_id)

        success = db.create_paper(paper)
        if success:
            log_service.log_user_action(user_id, 'create_paper', f"创建试卷: {paper.title}")
            return jsonify({'message': '试卷创建成功', 'paper_id': paper.id}), 201
        else:
            return jsonify({'error': '试卷创建失败'}), 500
    except Exception as e:
        print(f"创建试卷失败: {e}")
        return jsonify({'error': '创建试卷失败，请重试'}), 500


# 修复搜索试卷API
@app.route('/api/papers/search', methods=['GET'])
@require_login
def search_papers():
    try:
        filters = {}
        user_role = session.get('user_role')
        user_id = session.get('user_id')

        # 获取搜索参数
        if request.args.get('subject'):
            filters['subject'] = request.args.get('subject')
        if request.args.get('keyword'):
            filters['keyword'] = request.args.get('keyword')
        if request.args.get('creator_id'):
            filters['creator_id'] = request.args.get('creator_id')

        # 使用搜索方法而不是获取所有试卷
        papers = db.search_papers(filters) if filters else db.get_all_papers()
        papers_data = []
        for paper in papers:
            papers_data.append({
                'id': paper.id,
                'title': paper.title,
                'description': paper.description,
                'subject': paper.subject,
                'total_score': paper.total_score,
                'question_count': len(paper.questions),
                'created_time': paper.created_time.isoformat(),
                'can_edit': check_paper_ownership(paper.id, user_id, user_role),
                'can_delete': check_paper_ownership(paper.id, user_id, user_role)
            })
        return jsonify({'papers': papers_data})
    except Exception as e:
        print(f"搜索试卷失败: {e}")
        return jsonify({'error': '获取试卷列表失败'}), 500


# 新增：编辑试卷API
@app.route('/api/papers/<paper_id>', methods=['PUT'])
@require_login
@require_role(['admin', 'teacher'])
def update_paper(paper_id):
    data = request.get_json()
    user_id = session.get('user_id')
    user_role = session.get('user_role')

    if not check_paper_ownership(paper_id, user_id, user_role):
        return jsonify({'error': '您没有权限编辑此试卷'}), 403

    try:
        success = db.update_paper(paper_id, data)
        if success:
            log_service.log_user_action(user_id, 'update_paper', f"更新试卷: {paper_id}")
            return jsonify({'message': '试卷更新成功'}), 200
        else:
            return jsonify({'error': '试卷更新失败'}), 500
    except Exception as e:
        print(f"更新试卷失败: {e}")
        return jsonify({'error': '更新试卷时发生错误'}), 500


# 新增：删除试卷API
@app.route('/api/papers/<paper_id>', methods=['DELETE'])
@require_login
@require_role(['admin', 'teacher'])
def delete_paper(paper_id):
    user_id = session.get('user_id')
    user_role = session.get('user_role')

    if not check_paper_ownership(paper_id, user_id, user_role):
        return jsonify({'error': '您没有权限删除此试卷'}), 403

    try:
        success = db.delete_paper(paper_id)
        if success:
            log_service.log_user_action(user_id, 'delete_paper', f"删除试卷: {paper_id}")
            return jsonify({'message': '试卷删除成功'}), 200
        else:
            return jsonify({'error': '试卷删除失败'}), 500
    except Exception as e:
        print(f"删除试卷失败: {e}")
        return jsonify({'error': '删除试卷时发生错误'}), 500


@app.route('/api/papers/<paper_id>', methods=['GET'])
@require_login
def get_paper_detail(paper_id):
    """获取试卷详情"""
    try:
        paper = db.get_paper_by_id(paper_id)
        if not paper:
            return jsonify({'error': '试卷不存在'}), 404

        # 获取试卷中的所有试题详情
        questions = []
        if paper.questions:
            for q_data in paper.questions:
                question_id = q_data.get('question_id') if isinstance(q_data, dict) else q_data
                question = db.get_question_by_id(question_id)
                if question:
                    questions.append({
                        'id': question.id,
                        'content': question.content,
                        'question_type': question.question_type.value,
                        'difficulty': question.difficulty.value,
                        'subject': question.subject,
                        'chapter': question.chapter,
                        'answer': question.answer,
                        'explanation': question.explanation,
                        'score': q_data.get('score', 5) if isinstance(q_data, dict) else 5
                    })

        # 获取创建者信息
        creator = db.get_user_by_id(paper.creator_id)
        creator_name = creator.username if creator else '未知'

        return jsonify({
            'paper': {
                'id': paper.id,
                'name': paper.title,
                'description': paper.description,
                'subject': paper.subject,
                'total_score': paper.total_score,
                'creator_name': creator_name,
                'created_time': paper.created_time.isoformat()
            },
            'questions': questions
        })
    except Exception as e:
        print(f"获取试卷详情失败: {e}")
        return jsonify({'error': '获取试卷详情失败'}), 500


@app.route('/api/papers/<paper_id>/export', methods=['GET'])
@require_login
def export_paper(paper_id):
    """导出试卷为Word文档"""
    try:
        from docx import Document
        from io import BytesIO
        from flask import send_file

        paper = db.get_paper_by_id(paper_id)
        if not paper:
            return jsonify({'error': '试卷不存在'}), 404

        # 创建Word文档
        doc = Document()

        # 添加标题
        title = doc.add_heading(paper.title, 0)
        title.alignment = 1  # 居中对齐

        # 添加试卷信息
        doc.add_paragraph(f"科目：{paper.subject}")
        doc.add_paragraph(f"总分：{paper.total_score}分")
        doc.add_paragraph(f"题目数量：{len(paper.questions)}题")
        doc.add_paragraph(f"考试时间：120分钟")
        doc.add_paragraph("")  # 空行

        # 添加试题
        for i, q_data in enumerate(paper.questions, 1):
            question_id = q_data.get('question_id') if isinstance(q_data, dict) else q_data
            question = db.get_question_by_id(question_id)
            if question:
                score = q_data.get('score', 5) if isinstance(q_data, dict) else 5

                # 添加试题标题
                q_title = doc.add_paragraph(f"第{i}题({score}分)")
                q_title.bold = True

                # 添加试题内容
                doc.add_paragraph(question.content)

                # 如果是选择题，添加选项
                if question.question_type.value == 'multiple_choice' and question.options:
                    for opt in question.options:
                        doc.add_paragraph(f"  {opt}")

                doc.add_paragraph("")  # 空行

        # 保存到内存
        buffer = BytesIO()
        doc.save(buffer)
        buffer.seek(0)

        return send_file(
            buffer,
            as_attachment=True,
            download_name=f"{paper.title}.docx",
            mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )
    except ImportError:
        return jsonify({'error': '缺少python-docx库，请安装后重试'}), 500
    except Exception as e:
        print(f"导出试卷失败: {e}")
        return jsonify({'error': '导出试卷失败'}), 500


@app.route('/api/papers/smart-generate', methods=['POST'])
@require_login
@require_role(['admin', 'teacher'])
def smart_generate_paper():
    """智能组卷API"""
    data = request.get_json()
    user_id = session.get('user_id')

    try:
        # 获取难度分布
        difficulty_dist = data.get('difficulty_distribution', {})
        easy_count = difficulty_dist.get('easy', 0)
        medium_count = difficulty_dist.get('medium', 0)
        hard_count = difficulty_dist.get('hard', 0)
        very_hard_count = difficulty_dist.get('very_hard', 0)

        # 按难度查找试题
        subject = data.get('subject', '')
        all_questions = db.search_questions({'subject': subject} if subject else {})

        # 按难度分组
        easy_questions = [q for q in all_questions if q.difficulty.value == 1]
        medium_questions = [q for q in all_questions if q.difficulty.value == 2]
        hard_questions = [q for q in all_questions if q.difficulty.value == 3]
        very_hard_questions = [q for q in all_questions if q.difficulty.value == 4]

        # 选择试题
        selected_questions = []
        import random

        # 随机选择各难度试题
        selected_questions.extend(random.sample(easy_questions, min(easy_count, len(easy_questions))))
        selected_questions.extend(random.sample(medium_questions, min(medium_count, len(medium_questions))))
        selected_questions.extend(random.sample(hard_questions, min(hard_count, len(hard_questions))))
        selected_questions.extend(random.sample(very_hard_questions, min(very_hard_count, len(very_hard_questions))))

        if not selected_questions:
            return jsonify({'error': '没有找到符合条件的试题'}), 400

        # 创建试卷
        paper = Paper(
            id=str(uuid.uuid4()),
            title=data.get('name', '智能组卷试卷'),
            description=data.get('description', '智能生成的试卷'),
            subject=subject,
            questions=[{'question_id': q.id, 'score': 5} for q in selected_questions],
            total_score=len(selected_questions) * 5,
            creator_id=user_id,
            created_time=datetime.now()
        )

        success = db.create_paper(paper)
        if success:
            log_service.log_user_action(user_id, 'smart_generate_paper', f"智能组卷: {paper.title}")
            return jsonify({'message': f'智能组卷成功！共生成{len(selected_questions)}道题', 'paper_id': paper.id}), 201
        else:
            return jsonify({'error': '智能组卷失败'}), 500
    except Exception as e:
        print(f"智能组卷失败: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': '智能组卷失败，请重试'}), 500


@app.route('/api/statistics/overview', methods=['GET'])
@require_login
@require_role(['admin', 'teacher'])
def get_statistics_overview():
    stats = db.get_statistics()
    user_role = session.get('user_role')

    if user_role == 'teacher':
        filtered_stats = {
            'total_questions': stats['total_questions'],
            'total_papers': stats['total_papers'],
            'questions_by_subject': stats['questions_by_subject'],
            'difficulty_distribution': stats['difficulty_distribution']
        }
        return jsonify(filtered_stats)
    else:
        return jsonify(stats)


@app.route('/api/questions/similarity/batch-check', methods=['POST'])
@require_login
@require_role(['admin', 'teacher'])
def batch_similarity_check():
    """批量相似度检查API"""
    try:
        questions = db.search_questions()
        duplicates = []

        for i, q1 in enumerate(questions):
            for j, q2 in enumerate(questions[i + 1:], i + 1):
                similarity = enhanced_similarity_service._jaccard_similarity(q1.content, q2.content)
                if similarity >= 0.8:
                    duplicates.append({
                        'question1_id': q1.id,
                        'question2_id': q2.id,
                        'similarity': similarity,
                        'content1': q1.content[:100],
                        'content2': q2.content[:100]
                    })
                    # 保存相似度结果
                    db.save_similarity_result(q1.id, q2.id, similarity)

        return jsonify({
            'duplicates': duplicates,
            'total_checked': len(questions),
            'duplicate_pairs': len(duplicates)
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/questions/<question_id>/similarity-history', methods=['GET'])
@require_login
def get_similarity_history(question_id):
    """获取试题相似度检查历史"""
    try:
        history = db.get_similarity_history(question_id)
        return jsonify({'similarity_history': history})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


# ==================== 新增：难度分析API ====================

@app.route('/api/questions/<question_id>/difficulty-analysis', methods=['POST'])
@require_login
@require_role(['admin', 'teacher'])
def analyze_question_difficulty(question_id):
    """分析试题难度"""
    try:
        question = db.get_question_by_id(question_id)
        if not question:
            return jsonify({'error': '试题不存在'}), 404

        analysis = enhanced_difficulty_service.analyze_question_difficulty(question)
        return jsonify(analysis)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/papers/<paper_id>/difficulty-analysis', methods=['GET'])
@require_login
def analyze_paper_difficulty(paper_id):
    """分析试卷难度"""
    try:
        analysis = db.get_paper_difficulty_analysis(paper_id)
        return jsonify({'difficulty_analysis': analysis})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


# ==================== 新增：考察记录API ====================

@app.route('/api/exam-records', methods=['POST'])
@require_login
@require_role(['admin', 'teacher'])
def add_exam_record():
    """添加考察记录"""
    try:
        data = request.get_json()
        question_id = data.get('question_id')
        exam_date = datetime.fromisoformat(data.get('exam_date', datetime.now().isoformat()))
        exam_name = data.get('exam_name', '')
        paper_id = data.get('paper_id', '')
        knowledge_points = data.get('knowledge_points', [])

        success = db.add_exam_record(
            question_id, exam_date, exam_name, paper_id, knowledge_points
        )

        if success:
            return jsonify({'message': '考察记录添加成功'})
        else:
            return jsonify({'error': '添加考察记录失败'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/questions/<question_id>/exam-history', methods=['GET'])
@require_login
def get_question_exam_history(question_id):
    """获取试题考察历史"""
    try:
        history = db.get_question_exam_history(question_id)
        return jsonify({'exam_history': history})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/statistics/exam-frequency', methods=['GET'])
@require_login
@require_role(['admin', 'teacher'])
def get_exam_frequency_stats():
    """获取考察频次统计"""
    try:
        subject = request.args.get('subject')
        days = int(request.args.get('days', 365))

        from datetime import timedelta
        start_date = datetime.now() - timedelta(days=days)

        stats = db.get_exam_frequency_stats(
            start_date=start_date,
            subject=subject
        )

        return jsonify(stats)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


# ==================== 新增：增强统计API ====================

@app.route('/api/statistics/comprehensive', methods=['GET'])
@require_login
@require_role(['admin', 'teacher'])
def get_comprehensive_statistics():
    """获取综合统计数据"""
    try:
        stats = db.get_comprehensive_statistics()
        return jsonify(stats)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 前端页面 - 修复JavaScript问题
@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>
<html>
<head>
    <title>试题管理系统</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }
        .header {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
        }
        .header h1 {
            margin: 0 0 10px 0;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }
        .nav {
            background: rgba(248, 249, 250, 0.9);
            padding: 20px;
            margin: 20px 0;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .content {
            background: rgba(255, 255, 255, 0.9);
            padding: 30px;
            border-radius: 10px;
            min-height: 500px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        button {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            margin: 8px;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
            box-shadow: 0 2px 10px rgba(0, 123, 255, 0.3);
        }
        button:hover {
            background: linear-gradient(135deg, #0056b3, #004085);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0, 123, 255, 0.4);
        }
        button:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997) !important;
            box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3) !important;
        }
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333) !important;
            box-shadow: 0 2px 10px rgba(220, 53, 69, 0.3) !important;
        }
        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800) !important;
            box-shadow: 0 2px 10px rgba(255, 193, 7, 0.3) !important;
            color: #212529 !important;
        }
        input, textarea, select {
            width: 100%;
            padding: 12px;
            margin: 8px 0;
            border: 1px solid rgba(221, 221, 221, 0.8);
            border-radius: 8px;
            box-sizing: border-box;
            background: rgba(255, 255, 255, 0.9);
            transition: all 0.3s ease;
            font-size: 14px;
        }
        input:focus, textarea:focus, select:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
            outline: none;
        }
        .form-group {
            margin: 20px 0;
        }
        .form-group label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }
        .alert {
            padding: 15px;
            margin: 15px 0;
            border-radius: 8px;
            border-left: 4px solid;
            backdrop-filter: blur(5px);
        }
        .alert-success {
            background: rgba(212, 237, 218, 0.9);
            color: #155724;
            border-left-color: #28a745;
        }
        .alert-error {
            background: rgba(248, 215, 218, 0.9);
            color: #721c24;
            border-left-color: #dc3545;
        }
        .alert-warning {
            background: rgba(255, 243, 205, 0.9);
            color: #856404;
            border-left-color: #ffc107;
        }
        .question-item, .paper-item, .user-item {
            border: 1px solid rgba(221, 221, 221, 0.6);
            padding: 20px;
            margin: 15px 0;
            border-radius: 10px;
            background: rgba(249, 249, 249, 0.9);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        .question-item:hover, .paper-item:hover, .user-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }
        .search-filters {
            background: rgba(248, 249, 250, 0.9);
            padding: 20px;
            border-radius: 10px;
            margin: 15px 0;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .search-filters .form-group {
            display: inline-block;
            width: 48%;
            margin-right: 2%;
            vertical-align: top;
        }
        .role-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 10px;
        }
        .role-admin { background: #dc3545; color: white; }
        .role-teacher { background: #28a745; color: white; }
        .role-assistant { background: #6c757d; color: white; }
        .permission-denied {
            background: rgba(255, 243, 205, 0.9);
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 15px;
            margin: 15px 0;
            color: #856404;
            text-align: center;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .stats-card {
            background: rgba(248, 249, 250, 0.9);
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        .stats-card h3 {
            font-size: 2.5em;
            margin: 0 0 10px 0;
            color: #007bff;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
            font-style: italic;
        }
        .no-data {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        .form-row {
            display: flex;
            gap: 15px;
        }
        .form-row .form-group {
            flex: 1;
        }
        @media (max-width: 768px) {
            .container { margin: 10px; padding: 15px; }
            .header h1 { font-size: 2em; }
            .form-row { flex-direction: column; }
            .search-filters .form-group { width: 100%; margin-right: 0; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎓试题管理系统</h1>
            <p>智能化试题管理与组卷系统</p>
            <div id="user-info" style="margin-top: 15px; font-size: 14px;"></div>
        </div>

        <div class="nav">
            <button onclick="showLogin()">🔐登录</button>
            <button onclick="showRegister()">📝注册</button>
            <button onclick="showQuestions()" id="btn-questions">📚试题管理</button>
            <button onclick="showPapers()" id="btn-papers">📄试卷管理</button>
            <button onclick="showStats()" id="btn-stats" style="display: none;">📊数据统计</button>            <button onclick="showEnhancedFeatures()" id="btn-enhanced" style="display:none;">🚀增强功能</button>
            <button onclick="showUserManagement()" id="btn-users" style="display:none;">👥用户管理</button>
            <button onclick="logout()" id="btn-logout" style="display:none;">🚪登出</button>
        </div>

        <div class="content" id="main-content">
            <h2>🌟欢迎使用试题管理系统</h2>
            <div style="margin-bottom: 30px;">
                <h3>👥角色权限说明</h3>
                <div style="background: rgba(248, 249, 250, 0.9); padding: 20px; border-radius: 10px;">
                    <div style="margin-bottom: 15px;">
                        <span class="role-badge role-admin">管理员</span>
                        <span style="margin-left: 10px;">✅完全权限：可以管理所有试题、试卷和用户</span>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <span class="role-badge role-teacher">教师</span>
                        <span style="margin-left: 10px;">📝创建权限：可以创建试题和试卷，编辑自己的内容</span>
                    </div>
                    <div>
                        <span class="role-badge role-assistant">助教</span>
                        <span style="margin-left: 10px;">👀查看权限：只能查看试题和试卷，不能编辑</span>
                    </div>
                </div>
            </div>

            <h3>🚀系统功能</h3>
            <ul style="line-height: 2; font-size: 16px;">
                <li>📚<strong>试题资源管理</strong> - 支持试题的增删改查、批量导入导出</li>
                <li>🤖<strong>智能组卷</strong> - 根据知识点覆盖、难度分布等条件自动组卷</li>
                <li>🔍<strong>试题查重</strong> - 自动检测重复或相似试题</li>
                <li>📈<strong>难度分析</strong> - 基于历史数据分析试题和试卷难度</li>
                <li>📊<strong>考察统计</strong> - 跟踪试题使用情况和考察频次</li>
                <li>👥<strong>用户权限管理</strong> - 支持管理员、教师、助教三种角色</li>
            </ul>

            <div style="margin-top: 30px; padding: 20px; background: rgba(0, 123, 255, 0.1); border-radius: 10px; border-left: 4px solid #007bff;">
                <p><strong>💡提示：</strong>请先登录系统以开始使用</p>
                <p><strong>🔑默认账户：</strong></p>
                <p>👨‍💼管理员：<code>admin</code> / <code>admin123</code></p>
                <p>👨‍🏫教师：<code>teacher</code> / <code>teacher123</code></p>
                <p>👨‍🎓助教：<code>assistant</code> / <code>assistant123</code></p>
            </div>
        </div>
    </div>

<script>
let currentUser = null;
let currentQuestionDraft = null;

window.onload = function() {
    checkLoginStatus();
};

async function checkLoginStatus() {
    console.log('页面已加载，等待用户登录');
}

function updateUIForLoggedInUser(user) {
    document.getElementById('user-info').innerHTML = `
        👤当前用户：${user.username}
        <span class="role-badge role-${user.role}">${getRoleText(user.role)}</span>
    `;

    document.getElementById('btn-logout').style.display = 'inline-block';

    // 重置所有按钮状态
    document.getElementById('btn-papers').style.opacity = '1';
    document.getElementById('btn-stats').style.opacity = '1';
    document.getElementById('btn-enhanced').style.display = 'none';  // 新增
    document.getElementById('btn-users').style.display = 'none';

    if (user.role === 'admin') {
        document.getElementById('btn-users').style.display = 'inline-block';
        document.getElementById('btn-enhanced').style.display = 'inline-block';  // 管理员可以使用增强功能
    }

    if (user.role === 'teacher') {
        document.getElementById('btn-enhanced').style.display = 'inline-block';  // 教师也可以使用增强功能
    }

    if (user.role === 'assistant') {
        document.getElementById('btn-stats').style.opacity = '0.6';
        document.getElementById('btn-papers').style.opacity = '1';
        // 助教不显示增强功能按钮
    }
}

function getRoleText(role) {
    const roleMap = {
        'admin': '管理员',
        'teacher': '教师',
        'assistant': '助教'
    };
    return roleMap[role] || role;
}

function showLogin() {
    document.getElementById('main-content').innerHTML = `
    <h2>🔐用户登录</h2>
    <div class="form-group">
        <label>用户名：</label>
        <input type="text" id="username" placeholder="请输入用户名" autocomplete="off">
    </div>
    <div class="form-group">
        <label>密码：</label>
        <input type="password" id="password" placeholder="请输入密码" autocomplete="new-password">
    </div>
    <button onclick="login()">登录</button>
    <div style="margin-top: 30px; padding: 20px; background: rgba(0, 123, 255, 0.1); border-radius: 10px;">
        <h4>🔑测试账户</h4>
        <p>👨‍💼管理员：admin / admin123</p>
        <p>👨‍🏫教师：teacher / teacher123</p>
        <p>👨‍🎓助教：assistant / assistant123</p>
    </div>
    `;
}

function showRegister() {
    document.getElementById('main-content').innerHTML = `
        <h2>📝用户注册</h2>
        <div class="form-row">
            <div class="form-group">
                <label>用户名：</label>
                <input type="text" id="reg-username" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label>邮箱：</label>
                <input type="email" id="reg-email" placeholder="请输入邮箱">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>密码：</label>
                <input type="password" id="reg-password" placeholder="请输入密码">
            </div>
            <div class="form-group">
                <label>角色：</label>
                <select id="reg-role">
                    <option value="assistant">👨‍🎓助教</option>
                    <option value="teacher">👨‍🏫教师</option>
                    <option value="admin">👨‍💼管理员</option>
                </select>
            </div>
        </div>
        <button onclick="register()">注册</button>
    `;
}

async function showQuestions() {
    if (!currentUser) {
        alert('请先登录');
        return;
    }

    let html = `<h2>📚试题管理</h2>`;

    if (currentUser.role === 'assistant') {
        html += `
            <div class="permission-denied">
                ⚠️您当前是助教角色，只能查看试题，不能创建或编辑试题
            </div>
        `;
    } else {
        html += `
            <button onclick="showCreateQuestion()" class="btn-success">➕创建试题</button>
        `;
    }

    html += `
        <button onclick="searchQuestions()">🔍搜索试题</button>

        <div class="search-filters">
            <h4>🔍搜索筛选</h4>
            <div class="form-group">
                <label>学科筛选：</label>
                <select id="search-subject">
                    <option value="">全部学科</option>
                </select>
            </div>
            <div class="form-group">
                <label>难度筛选：</label>
                <select id="search-difficulty">
                    <option value="">全部难度</option>
                    <option value="1">简单</option>
                    <option value="2">中等</option>
                    <option value="3">困难</option>
                    <option value="4">非常困难</option>
                </select>
            </div>
            <div class="form-group">
                <label>关键词搜索：</label>
                <input type="text" id="search-keyword" placeholder="请输入关键词">
            </div>
        </div>

        <div id="question-list"></div>
    `;

    document.getElementById('main-content').innerHTML = html;

    // 加载学科选项
    try {
        const response = await fetch('/api/subjects');
        const data = await response.json();
        if (data.subjects) {
            const subjectSelect = document.getElementById('search-subject');
            data.subjects.forEach(subject => {
                const option = document.createElement('option');
                option.value = subject;
                option.textContent = subject;
                subjectSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载学科列表失败:', error);
    }
}

function showCreateQuestion() {
    if (currentUser.role === 'assistant') {
        alert('助教没有权限创建试题');
        return;
    }

    document.getElementById('main-content').innerHTML = `
        <h2>➕创建试题</h2>
        <div class="form-group">
            <label>试题内容：</label>
            <textarea id="question-content" rows="4" placeholder="请输入试题内容"></textarea>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>试题类型：</label>
                <select id="question-type">
                    <option value="multiple_choice">单选题</option>
                    <option value="true_false">判断题</option>
                    <option value="fill_blank">填空题</option>
                    <option value="short_answer">简答题</option>
                    <option value="essay">论述题</option>
                </select>
            </div>
            <div class="form-group">
                <label>难度：</label>
                <select id="question-difficulty">
                    <option value="1">简单</option>
                    <option value="2" selected>中等</option>
                    <option value="3">困难</option>
                    <option value="4">非常困难</option>
                </select>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>学科：</label>
                <input type="text" id="question-subject" placeholder="请输入学科">
            </div>
            <div class="form-group">
                <label>章节：</label>
                <input type="text" id="question-chapter" placeholder="请输入章节（可选）">
            </div>
        </div>
        <div class="form-group">
            <label>答案：</label>
            <input type="text" id="question-answer" placeholder="请输入答案">
        </div>
        <div class="form-group">
            <label>解析：</label>
            <textarea id="question-explanation" rows="3" placeholder="请输入解析（可选）"></textarea>
        </div>
        <button onclick="createQuestion()" class="btn-success">✅创建试题</button>
        <button onclick="showQuestions()">↩️返回</button>
    `;
}

async function showPapers() {
    if (!currentUser) {
        alert('请先登录');
        return;
    }

    let html = `<h2>📄试卷管理</h2>`;

    if (currentUser.role === 'assistant') {
        html += `
            <div class="permission-denied">
                ⚠️您当前是助教角色，只能查看试卷，不能创建试卷
            </div>
        `;
    } else {
        // 修复1: 将搜索按钮与创建按钮并排
        html += `
            <div style="margin-bottom: 20px;">
                <button onclick="showCreatePaper()" class="btn-success">📝手动创建试卷</button>
                <button onclick="showAutoCreatePaper()" class="btn-warning">🤖智能组卷</button>
                <button onclick="searchPapers()" style="background: #17a2b8; color: white;">🔍搜索试卷</button>
            </div>
        `;
    }

    if (currentUser.role === 'assistant') {
        // 助教也能搜索试卷
        html += `
            <div style="margin-bottom: 20px;">
                <button onclick="searchPapers()" style="background: #17a2b8; color: white;">🔍搜索试卷</button>
            </div>
        `;
    }

    html += `
        <div class="search-filters">
            <h4>🔍搜索筛选</h4>
            <div class="form-group">
                <label>学科筛选：</label>
                <select id="paper-search-subject">
                    <option value="">全部学科</option>
                </select>
            </div>
            <div class="form-group">
                <label>关键词搜索：</label>
                <input type="text" id="paper-search-keyword" placeholder="请输入试卷名称或描述关键词">
            </div>
        </div>

        <div id="paper-list"></div>
    `;

    document.getElementById('main-content').innerHTML = html;

    // 加载学科选项到搜索筛选中
    try {
        const response = await fetch('/api/subjects');
        const data = await response.json();
        if (data.subjects) {
            const subjectSelect = document.getElementById('paper-search-subject');
            data.subjects.forEach(subject => {
                const option = document.createElement('option');
                option.value = subject;
                option.textContent = subject;
                subjectSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载学科列表失败:', error);
    }

    // 自动加载试卷列表
    searchPapers();
}

async function showCreatePaper() {
    // 修复2: 动态加载科目选项
    let subjectOptions = '<option value="">选择科目</option>';

    try {
        const response = await fetch('/api/subjects');
        const data = await response.json();
        if (data.subjects && data.subjects.length > 0) {
            subjectOptions = '<option value="">选择科目</option>';
            data.subjects.forEach(subject => {
                subjectOptions += `<option value="${subject}">${subject}</option>`;
            });
        } else {
            // 如果数据库中没有科目，提供常用科目作为备选
            subjectOptions = `
                <option value="">选择科目</option>
                <option value="数学">数学</option>
                <option value="语文">语文</option>
                <option value="英语">英语</option>
                <option value="物理">物理</option>
                <option value="化学">化学</option>
                <option value="生物">生物</option>
                <option value="历史">历史</option>
                <option value="地理">地理</option>
                <option value="政治">政治</option>
            `;
        }
    } catch (error) {
        console.error('加载科目失败:', error);
        // 出错时使用默认科目
        subjectOptions = `
            <option value="">选择科目</option>
            <option value="数学">数学</option>
            <option value="语文">语文</option>
            <option value="英语">英语</option>
            <option value="物理">物理</option>
            <option value="化学">化学</option>
            <option value="生物">生物</option>
        `;
    }

    document.getElementById('main-content').innerHTML = `
        <h2>📝手动创建试卷</h2>
        <form id="create-paper-form" style="background: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <label><strong>📋试卷名称:</strong></label>
                    <input type="text" id="paper-name" placeholder="请输入试卷名称" style="width: 100%; padding: 8px; margin-top: 5px;">
                </div>
                <div>
                    <label><strong>📚科目:</strong></label>
                    <select id="paper-subject" style="width: 100%; padding: 8px; margin-top: 5px;">
                        ${subjectOptions}
                    </select>
                    <small style="color: #666; display: block; margin-top: 5px;">💡如果没有您需要的科目，请先创建该科目的试题</small>
                </div>
            </div>
            <div style="margin-bottom: 20px;">
                <label><strong>📝描述:</strong></label>
                <textarea id="paper-description" placeholder="试卷描述（可选）" style="width: 100%; padding: 8px; margin-top: 5px; height: 80px;"></textarea>
            </div>
            <button type="button" onclick="showQuestionSelector()" style="background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px;">
                🔍选择试题
            </button>
            <button type="button" onclick="showPapers()" style="background: #6c757d; color: white; padding: 10px 20px; border: none; border-radius: 5px; margin-left: 10px;">
                ↩️返回
            </button>
        </form>

        <!-- 试题选择区域 -->
        <div id="question-selector" style="display: none;">
            <div style="background: white; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
                <h3>🔍搜索和选择试题</h3>
                <div style="display: flex; gap: 15px; margin-bottom: 15px; flex-wrap: wrap;">
                    <select id="search-subject" style="padding: 8px;">
                        <option value="">全部科目</option>
                    </select>
                    <select id="search-difficulty" style="padding: 8px;">
                        <option value="">全部难度</option>
                        <option value="1">简单</option>
                        <option value="2">中等</option>
                        <option value="3">困难</option>
                        <option value="4">非常困难</option>
                    </select>
                    <input type="text" id="search-keyword" placeholder="搜索试题内容..." style="padding: 8px; flex: 1; min-width: 200px;">
                    <button onclick="searchQuestionsForPaper()" style="background: #28a745; color: white; padding: 8px 15px; border: none; border-radius: 4px;">🔍搜索</button>
                </div>
                <div id="available-questions"></div>
            </div>

            <!-- 已选试题 -->
            <div style="background: white; padding: 20px; border-radius: 10px;">
                <h3>📋已选试题(<span id="selected-count">0</span>道)</h3>
                <div id="selected-questions" style="min-height: 100px; border: 2px dashed #ddd; padding: 15px; border-radius: 8px;">
                    <p style="color: #999; text-align: center;">暂未选择试题</p>
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button onclick="createPaperWithSelectedQuestions()" style="background: #007bff; color: white; padding: 12px 30px; border: none; border-radius: 6px; font-size: 16px;">
                        📝创建试卷
                    </button>
                    <button onclick="clearSelectedQuestions()" style="background: #dc3545; color: white; padding: 12px 20px; border: none; border-radius: 6px; margin-left: 10px;">
                        🗑️清空选择
                    </button>
                </div>
            </div>
        </div>
    `;

    // 为试题选择器加载科目选项
    try {
        const response = await fetch('/api/subjects');
        const data = await response.json();
        if (data.subjects) {
            const searchSubjectSelect = document.getElementById('search-subject');
            data.subjects.forEach(subject => {
                const option = document.createElement('option');
                option.value = subject;
                option.textContent = subject;
                searchSubjectSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载科目选项失败:', error);
    }

    // 存储已选试题
    window.selectedQuestions = [];
}

// 修复：确保函数定义
function showQuestionSelector() {
    const selector = document.getElementById('question-selector');
    if (selector) {
        selector.style.display = 'block';
        searchQuestionsForPaper(); // 初始加载所有试题
    } else {
        console.error('找不到question-selector元素');
    }
}

async function searchQuestionsForPaper() {
    try {
        const params = new URLSearchParams();
        const subject = document.getElementById('search-subject')?.value || '';
        const difficulty = document.getElementById('search-difficulty')?.value || '';
        const keyword = document.getElementById('search-keyword')?.value || '';

        if (subject) params.append('subject', subject);
        if (difficulty) params.append('difficulty', difficulty);
        if (keyword) params.append('keyword', keyword);

        const response = await fetch(`/api/questions/search?${params}`);
        const data = await response.json();

        if (response.ok) {
            displayAvailableQuestions(data.questions);
        } else {
            alert('搜索失败：' + data.error);
        }
    } catch (error) {
        console.error('搜索试题失败:', error);
        alert('搜索试题失败，请重试');
    }
}

function displayAvailableQuestions(questions) {
    const container = document.getElementById('available-questions');
    if (!container) return;

    if (!questions || questions.length === 0) {
        container.innerHTML = '<p style="text-align: center; color: #999;">未找到符合条件的试题</p>';
        return;
    }

    const questionsHtml = questions.map(q => {
        const isSelected = window.selectedQuestions && window.selectedQuestions.some(sq => sq.id === q.id);
        return `
            <div class="question-item" style="border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 8px; ${isSelected ? 'background: #e8f5e8; border-color: #28a745;' : 'background: white;'}">
                <div style="display: flex; justify-content: space-between; align-items: start;">
                    <div style="flex: 1;">
                        <div style="margin-bottom: 8px;">
                            <span style="background: #e3f2fd; padding: 4px 8px; border-radius: 4px; font-size: 12px;">${q.question_type}</span>
                            <span style="background: #f3e5f5; padding: 4px 8px; border-radius: 4px; font-size: 12px; margin-left: 5px;">难度: ${['', '简单', '中等', '困难', '非常困难'][q.difficulty]}</span>
                            <span style="background: #e8f5e9; padding: 4px 8px; border-radius: 4px; font-size: 12px; margin-left: 5px;">${q.subject} - ${q.chapter || '无章节'}</span>
                        </div>
                        <div style="font-weight: bold; margin-bottom: 8px;">
                            ${q.content.substring(0, 100)}${q.content.length > 100 ? '...' : ''}
                        </div>
                        <div style="color: #666; font-size: 14px;">
                            答案: ${q.answer.substring(0, 50)}${q.answer.length > 50 ? '...' : ''}
                        </div>
                    </div>
                    <button onclick="toggleQuestionSelection('${q.id}', \`${q.content.replace(/'/g, "\\'")}\`, '${q.question_type}', ${q.difficulty}, '${q.subject}', '${q.chapter || ''}', \`${q.answer.replace(/'/g, "\\'")}\`, \`${(q.explanation || '').replace(/'/g, "\\'")}\`)" 
                            style="background: ${isSelected ? '#dc3545' : '#28a745'}; color: white; border: none; padding: 8px 15px; border-radius: 4px; white-space: nowrap;">
                        ${isSelected ? '❌移除' : '✅选择'}
                    </button>
                </div>
            </div>
        `;
    }).join('');

    container.innerHTML = `
        <div style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px;">
            ${questionsHtml}
        </div>
    `;
}

function toggleQuestionSelection(id, content, type, difficulty, subject, chapter, answer, explanation) {
    if (!window.selectedQuestions) {
        window.selectedQuestions = [];
    }

    const existingIndex = window.selectedQuestions.findIndex(q => q.id === id);

    if (existingIndex >= 0) {
        window.selectedQuestions.splice(existingIndex, 1);
    } else {
        window.selectedQuestions.push({
            id, content, question_type: type, difficulty, subject, chapter, answer, explanation
        });
    }

    updateSelectedQuestionsDisplay();
    searchQuestionsForPaper(); // 刷新显示
}

function updateSelectedQuestionsDisplay() {
    const container = document.getElementById('selected-questions');
    const countElement = document.getElementById('selected-count');

    if (!window.selectedQuestions) {
        window.selectedQuestions = [];
    }

    if (countElement) countElement.textContent = window.selectedQuestions.length;

    if (!container) return;

    if (window.selectedQuestions.length === 0) {
        container.innerHTML = '<p style="color: #999; text-align: center;">暂未选择试题</p>';
        return;
    }

    const selectedHtml = window.selectedQuestions.map((q, index) => `
        <div style="border: 1px solid #28a745; padding: 12px; margin: 8px 0; border-radius: 6px; background: #f8fff8;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div style="flex: 1;">
                    <strong>${index + 1}. </strong>
                    <span style="background: #e3f2fd; padding: 2px 6px; border-radius: 3px; font-size: 11px;">${q.question_type}</span>
                    <span style="background: #f3e5f5; padding: 2px 6px; border-radius: 3px; font-size: 11px; margin-left: 5px;">${['', '简单', '中等', '困难', '非常困难'][q.difficulty]}</span>
                    <span style="margin-left: 10px;">${q.content.substring(0, 80)}${q.content.length > 80 ? '...' : ''}</span>
                </div>
                <button onclick="toggleQuestionSelection('${q.id}', \`${q.content.replace(/'/g, "\\'")}\`, '${q.question_type}', ${q.difficulty}, '${q.subject}', '${q.chapter || ''}', \`${q.answer.replace(/'/g, "\\'")}\`, \`${(q.explanation || '').replace(/'/g, "\\'")}\`)" 
                        style="background: #dc3545; color: white; border: none; padding: 6px 12px; border-radius: 4px;">
                    ❌移除
                </button>
            </div>
        </div>
    `).join('');

    container.innerHTML = selectedHtml;
}

function clearSelectedQuestions() {
    if (window.selectedQuestions && window.selectedQuestions.length > 0 && confirm('确定要清空所有已选试题吗？')) {
        window.selectedQuestions = [];
        updateSelectedQuestionsDisplay();
        searchQuestionsForPaper();
    }
}

async function createPaperWithSelectedQuestions() {
    const paperName = document.getElementById('paper-name')?.value || '';
    const paperSubject = document.getElementById('paper-subject')?.value || '';
    const paperDescription = document.getElementById('paper-description')?.value || '';

    if (!paperName.trim()) {
        alert('请输入试卷名称');
        return;
    }

    if (!window.selectedQuestions || window.selectedQuestions.length === 0) {
        alert('请至少选择一道试题');
        return;
    }

    try {
        const paperData = {
            name: paperName.trim(),
            subject: paperSubject,
            description: paperDescription.trim(),
            question_ids: window.selectedQuestions.map(q => q.id)
        };

        const response = await fetch('/api/papers', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(paperData)
        });

        const data = await response.json();

        if (response.ok) {
            alert(`✅试卷创建成功！\\n📋试卷名称：${paperName}\\n📝包含试题：${window.selectedQuestions.length}道`);
            showPapers();
        } else {
            alert('❌' + (data.error || '试卷创建失败'));
        }
    } catch (error) {
        console.error('创建试卷失败:', error);
        alert('❌创建试卷失败，请重试');
    }
}

function showAutoCreatePaper() {
    document.getElementById('main-content').innerHTML = `
        <h2>🤖智能组卷</h2>
        <div class="form-row">
            <div class="form-group">
                <label>试卷名称：</label>
                <input type="text" id="smart-paper-name" placeholder="请输入试卷名称">
            </div>
            <div class="form-group">
                <label>学科：</label>
                <input type="text" id="smart-paper-subject" placeholder="请输入学科">
            </div>
        </div>
        <div style="margin-bottom: 20px;">
            <label><strong>⭐难度分布：</strong></label>
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 15px; margin-top: 10px;">
                <div class="form-group">
                    <label>🟢简单题数量：</label>
                    <input type="number" id="easy-count" min="0" value="4">
                </div>
                <div class="form-group">
                    <label>🟡中等题数量：</label>
                    <input type="number" id="medium-count" min="0" value="3">
                </div>
                <div class="form-group">
                    <label>🟠困难题数量：</label>
                    <input type="number" id="hard-count" min="0" value="2">
                </div>
                <div class="form-group">
                    <label>🔴非常困难题数量：</label>
                    <input type="number" id="very-hard-count" min="0" value="1">
                </div>
            </div>
            <div style="margin-top: 10px; color: #666; font-size: 14px;">
                💡建议比例 - 简单:中等:困难:非常困难 = 4:3:2:1
            </div>
        </div>
        <div class="form-group">
            <label>试卷描述：</label>
            <textarea id="smart-description" placeholder="试卷描述（可选）" rows="3"></textarea>
        </div>
        <button onclick="generateSmartPaper()" class="btn-warning">🚀智能组卷</button>
        <button onclick="showPapers()">↩️返回</button>
    `;
}

async function generateSmartPaper() {
    const paperData = {
        name: document.getElementById('smart-paper-name')?.value || '',
        subject: document.getElementById('smart-paper-subject')?.value || '',
        description: document.getElementById('smart-description')?.value || '',
        difficulty_distribution: {
            easy: parseInt(document.getElementById('easy-count')?.value) || 0,
            medium: parseInt(document.getElementById('medium-count')?.value) || 0,
            hard: parseInt(document.getElementById('hard-count')?.value) || 0,
            very_hard: parseInt(document.getElementById('very-hard-count')?.value) || 0
        }
    };

    if (!paperData.name) {
        alert('请输入试卷名称');
        return;
    }

    const totalQuestions = paperData.difficulty_distribution.easy + 
                          paperData.difficulty_distribution.medium + 
                          paperData.difficulty_distribution.hard + 
                          paperData.difficulty_distribution.very_hard;

    if (totalQuestions === 0) {
        alert('请至少设置一道试题');
        return;
    }

    try {
        const response = await fetch('/api/papers/smart-generate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(paperData)
        });

        const data = await response.json();

        if (response.ok) {
            alert(`✅${data.message}`);
            showPapers();
        } else {
            alert('❌' + (data.error || '智能组卷失败'));
        }
    } catch (error) {
        console.error('智能组卷失败:', error);
        alert('❌智能组卷失败，请重试');
    }
}

// 修复搜索试卷函数
async function searchPapers() {
    try {
        const params = new URLSearchParams();
        const subject = document.getElementById('paper-search-subject')?.value || '';
        const keyword = document.getElementById('paper-search-keyword')?.value || '';

        if (subject) params.append('subject', subject);
        if (keyword) params.append('keyword', keyword);

        const response = await fetch(`/api/papers/search?${params}`);
        const data = await response.json();

        let html = '<h3>🔍试卷搜索结果</h3>';

        if (data.papers && data.papers.length > 0) {
            html += `<p>共找到<strong>${data.papers.length}</strong>个试卷</p>`;
            for (const paper of data.papers) {
                html += `
                    <div class="paper-item">
                        <h4>📄${paper.title}</h4>
                        <p><strong>🆔ID：</strong><code>${paper.id}</code></p>
                        <p><strong>📚学科：</strong>${paper.subject}</p>
                        <p><strong>📝描述：</strong>${paper.description || '无'}</p>
                        <p><strong>📊统计：</strong>共${paper.question_count}题，总分${paper.total_score}分</p>
                        <p><small>⏰创建时间：${new Date(paper.created_time).toLocaleString()}</small></p>
                        <div style="margin-top: 15px;">
                            <button onclick="viewPaperDetail('${paper.id}')" class="btn-info">🔍查看详情</button>
                            <button onclick="exportPaper('${paper.id}')" class="btn-success">📤导出试卷</button>
                            ${paper.can_edit ? `<button onclick="editPaper('${paper.id}')" class="btn-warning">✏️编辑试卷</button>` : ''}
                            ${paper.can_delete ? `<button onclick="deletePaper('${paper.id}')" class="btn-danger">🗑️删除试卷</button>` : ''}
                        </div>
                    </div>
                `;
            }
        } else {
            html += '<div class="no-data">📭暂无试卷数据。</div>';
        }

        document.getElementById('paper-list').innerHTML = html;
    } catch (error) {
        document.getElementById('paper-list').innerHTML = '<div class="alert alert-error">❌搜索试卷失败，请重试</div>';
        console.error('搜索试卷失败:', error);
    }
}

// 新增：编辑试卷功能
async function editPaper(paperId) {
    try {
        const response = await fetch(`/api/papers/${paperId}`);
        const data = await response.json();

        if (response.ok && data.paper) {
            const paper = data.paper;
            const questions = data.questions || [];

            document.getElementById('main-content').innerHTML = `
                <h2>✏️编辑试卷</h2>
                <div class="form-group">
                    <label>试卷ID：</label>
                    <input type="text" value="${paper.id}" disabled style="background: #f5f5f5;">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>试卷名称：</label>
                        <input type="text" id="edit-paper-name" value="${paper.name}">
                    </div>
                    <div class="form-group">
                        <label>学科：</label>
                        <input type="text" id="edit-paper-subject" value="${paper.subject}">
                    </div>
                </div>
                <div class="form-group">
                    <label>描述：</label>
                    <textarea id="edit-paper-description" rows="3">${paper.description || ''}</textarea>
                </div>
                <div class="form-group">
                    <label>总分：</label>
                    <input type="number" id="edit-paper-score" value="${paper.total_score}">
                </div>
                <h3>📝试题列表</h3>
                <div id="edit-questions-list">
                    ${questions.map((q, index) => `
                        <div style="border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 8px;">
                            <strong>第${index + 1}题：</strong>${q.content.substring(0, 100)}${q.content.length > 100 ? '...' : ''}
                            <div style="margin-top: 10px;">
                                <strong>分值：</strong>
                                <input type="number" value="${q.score}" min="1" max="100" style="width: 80px; padding: 4px;" onchange="updateQuestionScore('${q.id}', this.value)">
                                分
                            </div>
                        </div>
                    `).join('')}
                </div>
                <button onclick="savePaperEdit('${paperId}')" class="btn-success">💾保存修改</button>
                <button onclick="showPapers()">↩️取消</button>
            `;

            // 存储当前试卷数据
            window.editingPaper = {
                id: paperId,
                questions: questions
            };
        } else {
            alert('❌获取试卷详情失败');
        }
    } catch (error) {
        console.error('获取试卷详情失败:', error);
        alert('❌获取试卷详情失败');
    }
}

function updateQuestionScore(questionId, newScore) {
    if (window.editingPaper && window.editingPaper.questions) {
        const question = window.editingPaper.questions.find(q => q.id === questionId);
        if (question) {
            question.score = parseInt(newScore) || 5;
        }
    }
}

async function savePaperEdit(paperId) {
    const paperData = {
        title: document.getElementById('edit-paper-name')?.value || '',
        subject: document.getElementById('edit-paper-subject')?.value || '',
        description: document.getElementById('edit-paper-description')?.value || '',
        total_score: parseInt(document.getElementById('edit-paper-score')?.value) || 0,
        questions: window.editingPaper ? window.editingPaper.questions.map(q => ({
            question_id: q.id,
            score: q.score
        })) : []
    };

    try {
        const response = await fetch(`/api/papers/${paperId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(paperData)
        });

        const data = await response.json();

        if (response.ok) {
            alert('✅试卷更新成功！');
            showPapers();
        } else {
            alert(`❌更新失败: ${data.error}`);
        }
    } catch (error) {
        console.error('更新试卷失败:', error);
        alert('❌更新试卷失败，请重试');
    }
}

// 新增：删除试卷功能
async function deletePaper(paperId) {
    if (!confirm('⚠️确定要删除这个试卷吗？删除后无法恢复！')) {
        return;
    }

    try {
        const response = await fetch(`/api/papers/${paperId}`, {
            method: 'DELETE'
        });

        const data = await response.json();

        if (response.ok) {
            alert('✅试卷删除成功！');
            searchPapers();
        } else {
            alert(`❌删除失败: ${data.error}`);
        }
    } catch (error) {
        console.error('删除试卷失败:', error);
        alert('❌删除试卷失败，请重试');
    }
}

async function viewPaperDetail(paperId) {
    try {
        const response = await fetch(`/api/papers/${paperId}`);
        const data = await response.json();

        if (response.ok) {
            const paper = data.paper;
            const questions = data.questions || [];

            const questionsHtml = questions.map((q, index) => `
                <div style="border: 1px solid #ddd; padding: 15px; margin: 15px 0; border-radius: 8px; background: #fafafa;">
                    <div style="margin-bottom: 10px;">
                        <strong style="color: #007bff;">第${index + 1}题</strong>
                        <span style="margin-left: 10px; background: #e3f2fd; padding: 4px 8px; border-radius: 4px; font-size: 12px;">${q.question_type}</span>
                        <span style="margin-left: 5px; background: #f3e5f5; padding: 4px 8px; border-radius: 4px; font-size: 12px;">难度: ${['', '简单', '中等', '困难', '非常困难'][q.difficulty]}</span>
                        <span style="margin-left: 5px; background: #e8f5e9; padding: 4px 8px; border-radius: 4px; font-size: 12px;">${q.subject}</span>
                        <span style="float: right; color: #ff6b6b; font-weight: bold;">${q.score}分</span>
                    </div>
                    <div style="margin-bottom: 12px; font-size: 16px; line-height: 1.6;">
                        <strong>题目：</strong>${q.content}
                    </div>
                    <div style="margin-bottom: 10px; color: #28a745;">
                        <strong>答案：</strong>${q.answer}
                    </div>
                    ${q.explanation ? `
                        <div style="color: #666; font-size: 14px;">
                            <strong>解析：</strong>${q.explanation}
                        </div>
                    ` : ''}
                </div>
            `).join('');

            document.getElementById('main-content').innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h2>📋试卷详情</h2>
                    <button onclick="showPapers()" class="btn-secondary">🔙返回列表</button>
                </div>

                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 12px; margin-bottom: 25px;">
                    <h3 style="margin: 0 0 15px 0;">📝${paper.name}</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                        <div>📚<strong>科目：</strong>${paper.subject || '未分类'}</div>
                        <div>📊<strong>题目数量：</strong>${questions.length}道</div>
                        <div>💯<strong>总分：</strong>${paper.total_score}分</div>
                        <div>👤<strong>创建者：</strong>${paper.creator_name}</div>
                        <div>📅<strong>创建时间：</strong>${new Date(paper.created_time).toLocaleString()}</div>
                    </div>
                    ${paper.description ? `<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-top: 15px;"><strong>📄描述：</strong>${paper.description}</div>` : ''}
                </div>

                <div style="background: white; padding: 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3>📝试题列表</h3>
                        <button onclick="exportPaper('${paperId}')" class="btn-success">📤导出试卷</button>
                    </div>
                    ${questions.length > 0 ? questionsHtml : '<p style="text-align: center; color: #999;">该试卷暂无试题</p>'}
                </div>
            `;
        } else {
            alert('❌' + (data.error || '获取试卷详情失败'));
        }
    } catch (error) {
        console.error('获取试卷详情失败:', error);
        alert('❌获取试卷详情失败');
    }
}

async function exportPaper(paperId) {
    try {
        const response = await fetch(`/api/papers/${paperId}/export`);
        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = `试卷_${paperId}_${new Date().toISOString().split('T')[0]}.docx`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            alert('✅试卷导出成功！');
        } else {
            const data = await response.json();
            alert('❌' + (data.error || '导出试卷失败'));
        }
    } catch (error) {
        console.error('导出试卷失败:', error);
        alert('❌导出试卷失败');
    }
}

function showStats() {
    if (!currentUser) {
        alert('请先登录');
        return;
    }

    if (currentUser.role === 'assistant') {
        document.getElementById('main-content').innerHTML = `
            <h2>📊数据统计</h2>
            <div class="permission-denied">
                ⚠️您当前是助教角色，没有权限查看统计数据<br>
                <button onclick="showEnhancedFeatures()" style="margin-top: 15px; background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
                    🚀 前往增强功能中心
                </button>
            </div>
        `;
        return;
    }

    // 直接跳转到增强功能中心
    showEnhancedFeatures();
    // 自动展示统计数据
    setTimeout(() => {
        showIntegratedStatistics();
    }, 500);
}

function showUserManagement() {
    if (!currentUser || currentUser.role !== 'admin') {
        alert('只有管理员可以管理用户');
        return;
    }

    document.getElementById('main-content').innerHTML = `
        <h2>👥用户管理</h2>
        <div id="user-list" class="loading">👥正在加载用户列表...</div>
    `;

    loadAllUsers();
}

async function login() {
    const username = document.getElementById('username')?.value || '';
    const password = document.getElementById('password')?.value || '';

    if (!username || !password) {
        alert('请输入用户名和密码');
        return;
    }

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();

        if (response.ok) {
            currentUser = data.user;
            updateUIForLoggedInUser(data.user);

            document.getElementById('main-content').innerHTML = `
                <div class="alert alert-success">🎉登录成功！欢迎${data.user.username}</div>
                <h2>👤用户信息</h2>
                <div style="background: rgba(248, 249, 250, 0.9); padding: 25px; border-radius: 10px; margin: 20px 0;">
                    <p><strong>👤用户名：</strong>${data.user.username}</p>
                    <p><strong>🎭角色：</strong>${getRoleText(data.user.role)} <span class="role-badge role-${data.user.role}">${getRoleText(data.user.role)}</span></p>
                    <p><strong>📧邮箱：</strong>${data.user.email}</p>
                </div>
                <h3>🚀快速开始</h3>
                <div style="margin-top: 20px;">
                    <button onclick="showQuestions()" class="btn-success">📚开始管理试题</button>
                    <button onclick="showPapers()">📄管理试卷</button>
                    <button onclick="showEnhancedFeatures()" ${data.user.role === 'assistant' ? 'disabled' : ''}>🚀增强功能中心</button>
                    ${data.user.role === 'admin' ? '<button onclick="showUserManagement()">👥管理用户</button>' : ''}
                </div>
            `;
        } else {
            document.getElementById('main-content').innerHTML += `
                <div class="alert alert-error">❌${data.error}</div>
            `;
        }
    } catch (error) {
        console.error('登录失败:', error);
        document.getElementById('main-content').innerHTML += `
            <div class="alert alert-error">❌登录失败，请检查网络连接</div>
        `;
    }
}

async function register() {
    const userData = {
        username: document.getElementById('reg-username')?.value || '',
        password: document.getElementById('reg-password')?.value || '',
        email: document.getElementById('reg-email')?.value || '',
        role: document.getElementById('reg-role')?.value || 'assistant'
    };

    if (!userData.username || !userData.password || !userData.email) {
        alert('请填写所有必填字段');
        return;
    }

    if (userData.role === 'admin') {
        const adminKey = prompt('🔐请输入管理员密钥:');
        if (adminKey !== '123456') {
            alert('❌管理员密钥错误！');
            return;
        }
        userData.admin_key = adminKey;
    }

    try {
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(userData)
        });

        const data = await response.json();

        if (response.ok) {
            document.getElementById('main-content').innerHTML = `
                <div class="alert alert-success">🎉${data.message}</div>
                <div style="text-align: center; margin-top: 30px;">
                    <p>注册成功！现在可以登录了。</p>
                    <button onclick="showLogin()">🔐去登录</button>
                </div>
            `;
        } else {
            document.getElementById('main-content').innerHTML += `
                <div class="alert alert-error">❌${data.error}</div>
            `;
        }
    } catch (error) {
        console.error('注册失败:', error);
        document.getElementById('main-content').innerHTML += `
            <div class="alert alert-error">❌注册失败，请重试</div>
        `;
    }
}

async function logout() {
    try {
        await fetch('/api/logout', { method: 'POST' });
        currentUser = null;

        // 重置UI状态
        document.getElementById('user-info').innerHTML = '';
        document.getElementById('btn-logout').style.display = 'none';
        document.getElementById('btn-users').style.display = 'none';
        document.getElementById('btn-papers').style.opacity = '1';
        document.getElementById('btn-stats').style.opacity = '1';

        // 重新加载页面
        location.reload();
    } catch (error) {
        console.error('登出失败:', error);
    }
}

async function createQuestion() {  
    const questionData = {  
        content: document.getElementById('question-content')?.value || '',  
        question_type: document.getElementById('question-type')?.value || 'multiple_choice',  
        subject: document.getElementById('question-subject')?.value || '',  
        chapter: document.getElementById('question-chapter')?.value || '',  
        difficulty: parseInt(document.getElementById('question-difficulty')?.value) || 2,  
        answer: document.getElementById('question-answer')?.value || '',  
        explanation: document.getElementById('question-explanation')?.value || '',  
        options: []  
    };  

    if (!questionData.content || !questionData.subject) {  
        alert('请填写试题内容和学科');  
        return;  
    }  

    // 在创建前先进行查重检测  
    console.log('开始查重检测...');  
    const duplicateCheck = await checkQuestionSimilarity(questionData.content);  

    if (duplicateCheck.hasSimilar) {  
        // 显示相似试题警告  
        let similarInfo = '';  
        duplicateCheck.similarQuestions.forEach((similar, index) => {  
            similarInfo += `  
                <div style="background: #fff3e0; padding: 10px; margin: 8px 0; border-radius: 6px; border-left: 4px solid #ff9800;">  
                    <div style="font-weight: bold; color: #e65100; margin-bottom: 5px;">  
                        相似度: ${(similar.similarity * 100).toFixed(1)}% (阈值: ${Math.round(duplicateCheck.threshold * 100)}%)  
                    </div>  
                    <div style="color: #666; font-size: 14px;">  
                        <strong>学科:</strong> ${similar.subject} | <strong>ID:</strong> ${similar.id}  
                    </div>  
                    <div style="color: #333; margin-top: 5px; font-size: 14px;">  
                        ${similar.content.substring(0, 150)}${similar.content.length > 150 ? '...' : ''}  
                    </div>  
                </div>  
            `;  
        });  

        document.getElementById('main-content').innerHTML += `  
            <div class="alert alert-warning" style="background: #fff8e1; border: 1px solid #ffcc02; padding: 20px; border-radius: 8px; margin: 15px 0;">  
                <h4 style="color: #f57c00; margin: 0 0 15px 0;">🔍 发现相似试题</h4>  
                <p style="color: #e65100; margin-bottom: 15px;">  
                    系统检测到 <strong>${duplicateCheck.similarQuestions.length}</strong> 道相似试题，相似度超过了设定阈值 <strong>${Math.round(duplicateCheck.threshold * 100)}%</strong>  
                </p>  
                <div style="max-height: 300px; overflow-y: auto; margin-bottom: 15px;">  
                    ${similarInfo}  
                </div>  
                <div style="display: flex; gap: 10px; align-items: center;">  
                    <button onclick="createQuestionForce()" class="btn-warning" style="background: #ff9800; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer;">  
                        ✅ 确认创建 (忽略相似度)  
                    </button>  
                    <button onclick="showQuestions()" style="background: #6c757d; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer;">  
                        ↩️ 重新编辑  
                    </button>  
                    <button onclick="adjustThresholdAndRetry()" style="background: #007bff; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer;">  
                        ⚙️ 调整阈值设置  
                    </button>  
                </div>  
                <div style="margin-top: 10px; padding: 10px; background: #e3f2fd; border-radius: 4px;">  
                    <small style="color: #1976d2;">  
                        💡 提示: 可以在"增强功能"→"系统配置中心"→"高级设置"中调整相似度阈值。当前阈值: ${Math.round(duplicateCheck.threshold * 100)}%  
                    </small>  
                </div>  
            </div>  
        `;  

        // 保存当前试题草稿  
        window.currentQuestionDraft = questionData;
        localStorage.setItem('currentQuestionDraft', JSON.stringify(questionData)); 
        return;  
    }  

    // 如果没有相似试题，直接创建  
    try {  
        const response = await fetch('/api/questions', {  
            method: 'POST',  
            headers: { 'Content-Type': 'application/json' },  
            body: JSON.stringify(questionData)  
        });  

        const data = await response.json();  
        if (response.ok) {  
            document.getElementById('main-content').innerHTML += `  
                <div class="alert alert-success" style="background: #e8f5e8; border: 1px solid #28a745; padding: 15px; border-radius: 8px; margin: 15px 0;">  
                    ✅ ${data.message}  
                    <button onclick="showQuestions()" style="margin-left: 15px; background: #28a745; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">  
                        📚 返回试题列表  
                    </button>  
                </div>  
            `;  
        } else {  
            document.getElementById('main-content').innerHTML += `  
                <div class="alert alert-error" style="background: #ffebee; border: 1px solid #f44336; padding: 15px; border-radius: 8px; margin: 15px 0;">  
                    ❌ ${data.error}  
                </div>  
            `;  
        }  
    } catch (error) {  
        console.error('创建试题失败:', error);  
        document.getElementById('main-content').innerHTML += `  
            <div class="alert alert-error" style="background: #ffebee; border: 1px solid #f44336; padding: 15px; border-radius: 8px; margin: 15px 0;">  
                ❌ 创建试题失败，请重试  
            </div>  
        `;  
    }  
}

function adjustThresholdAndRetry() {  
    showEnhancedModal('快速调整相似度阈值', `  
        <div style="padding: 20px;">  
            <p style="color: #666; margin-bottom: 20px;">  
                当前相似度阈值可能过于严格，您可以适当调高阈值来减少误报。  
            </p>  

            <div style="margin-bottom: 20px;">  
                <label style="display: block; font-size: 14px; margin-bottom: 8px; font-weight: 500;">  
                    相似度阈值设置  
                </label>  
                <input type="range" id="quick-threshold" min="0.5" max="1.0" step="0.05" value="${getSimilarityThreshold()}"   
                       style="width: 100%; margin-bottom: 8px;" onchange="updateQuickThreshold()">  
                <div style="text-align: center; font-size: 14px; color: #666;">  
                    当前: <span id="quick-threshold-value">${Math.round(getSimilarityThreshold() * 100)}%</span>  
                </div>  
            </div>  

            <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px;">  
                <h5 style="margin: 0 0 10px 0; color: #495057;">阈值建议:</h5>  
                <ul style="margin: 0; padding-left: 20px; color: #666; font-size: 14px;">  
                    <li><strong>90-95%:</strong> 严格模式 - 几乎完全相同才报警</li>  
                    <li><strong>80-90%:</strong> 标准模式 - 高度相似时报警</li>  
                    <li><strong>70-80%:</strong> 宽松模式 - 一般相似时报警</li>  
                    <li><strong>60-70%:</strong> 敏感模式 - 较低相似度也报警</li>  
                </ul>  
            </div>  
        </div>  
    `, function() {  
        // 保存新的阈值设置  
        const newThreshold = document.getElementById('quick-threshold').value;  
        const settings = loadEnhancedSettings();  
        settings.similarityThreshold = parseFloat(newThreshold);  
        localStorage.setItem('enhancedSystemSettings', JSON.stringify(settings));  
        localStorage.setItem('aiSimilarityThreshold', newThreshold);  

        // 关闭模态框  
        closeEnhancedModal();  

        // 显示设置成功消息  
        showThresholdSavedTip();  

        // 重新尝试创建试题  
        setTimeout(() => {  
            if (window.currentQuestionDraft) {  
                console.log('使用新阈值重新检测:', newThreshold);  
                createQuestion();  
            }  
        }, 1000);  
    });  
}

function updateQuickThreshold() {  
    const slider = document.getElementById('quick-threshold');  
    const display = document.getElementById('quick-threshold-value');  
    if (slider && display) {  
        display.textContent = Math.round(slider.value * 100) + '%';  
    }  
}

function getCurrentQuestionDraft() {
    // 优先从内存获取
    if (window.currentQuestionDraft) {
        return window.currentQuestionDraft;
    }
    
    // 从localStorage恢复
    try {
        const stored = localStorage.getItem('currentQuestionDraft');
        if (stored) {
            const draft = JSON.parse(stored);
            window.currentQuestionDraft = draft;
            return draft;
        }
    } catch (error) {
        console.warn('恢复草稿失败:', error);
    }
    
    // 从表单重新收集
    const formDraft = {
        content: document.getElementById('question-content')?.value || '',
        answer: document.getElementById('question-answer')?.value || '',
        subject: document.getElementById('question-subject')?.value || '',
        chapter: document.getElementById('question-chapter')?.value || '',
        difficulty: document.getElementById('question-difficulty')?.value || 2,
        explanation: document.getElementById('question-explanation')?.value || '',
        options: []
    };
    
    if (formDraft.content && formDraft.subject) {
        return formDraft;
    }
    
    return null;
}

async function createQuestionForce() {
    const questionDraft = getCurrentQuestionDraft();
    if (!questionDraft) {
        alert('未找到试题草稿，请重新创建');
        return;
    }
    
    questionDraft.force_create = true;
    
    try {
        const response = await fetch('/api/questions', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(questionDraft)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 成功后清理草稿
            window.currentQuestionDraft = null;
            localStorage.removeItem('currentQuestionDraft');
            
            document.getElementById('main-content').innerHTML += `
                <div class="alert alert-success">
                    ✅${data.message}
                    <button onclick="showQuestions()" style="margin-left: 15px;">📚返回试题列表</button>
                </div>
            `;
        } else {
            document.getElementById('main-content').innerHTML += `
                <div class="alert alert-error">❌${data.error}</div>
            `;
        }
    } catch (error) {
        console.error('强制创建试题失败:', error);
        document.getElementById('main-content').innerHTML += `
            <div class="alert alert-error">❌强制创建试题失败，请重试</div>
        `;
    }
}

async function searchQuestions() {
    const subject = document.getElementById('search-subject')?.value || '';
    const difficulty = document.getElementById('search-difficulty')?.value || '';
    const keyword = document.getElementById('search-keyword')?.value || '';

    let url = '/api/questions/search?';
    if (subject) url += `subject=${encodeURIComponent(subject)}&`;
    if (difficulty) url += `difficulty=${difficulty}&`;
    if (keyword) url += `keyword=${encodeURIComponent(keyword)}&`;

    try {
        const response = await fetch(url);
        const data = await response.json();

        let html = '<h3>🔍搜索结果</h3>';

        if (data.questions && data.questions.length > 0) {
            html += `<p>共找到<strong>${data.questions.length}</strong>个试题</p>`;
            for (const q of data.questions) {
                html += `
                    <div class="question-item">
                        <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                            <div style="flex: 1;">
                                <p><strong>🆔ID：</strong><code>${q.id}</code></p>
                                <p><strong>📚学科：</strong>${q.subject} | <strong>📖章节：</strong>${q.chapter || '无'} | <strong>⭐难度：</strong>${getDifficultyText(q.difficulty)} | <strong>📝类型：</strong>${getQuestionTypeText(q.question_type)}</p>
                                <p><strong>❓内容：</strong>${q.content}</p>
                                <p><strong>✅答案：</strong>${q.answer || '无'}</p>
                                ${q.explanation ? `<p><strong>💡解析：</strong>${q.explanation}</p>` : ''}
                                <p><small>⏰创建时间：${new Date(q.created_time).toLocaleString()} | 📊使用次数：${q.usage_count}</small></p>
                            </div>
                            <div style="margin-left: 20px;">
                                ${q.can_edit ? `<button onclick="editQuestion('${q.id}')" class="btn-warning">✏️编辑</button>` : '<button disabled>✏️无权编辑</button>'}
                                ${q.can_delete ? `<button onclick="deleteQuestion('${q.id}')" class="btn-danger">🗑️删除</button>` : '<button disabled>🗑️无权删除</button>'}
                            </div>
                        </div>
                    </div>
                `;
            }
        } else {
            html += '<div class="no-data">📭未找到符合条件的试题。</div>';
        }

        document.getElementById('question-list').innerHTML = html;
    } catch (error) {
        document.getElementById('question-list').innerHTML = '<div class="alert alert-error">❌搜索失败，请重试</div>';
        console.error('搜索试题失败:', error);
    }
}

async function editQuestion(questionId) {
    try {
        const response = await fetch(`/api/questions/${questionId}`);
        const data = await response.json();

        if (response.ok && data.question) {
            const q = data.question;

            document.getElementById('main-content').innerHTML = `
                <h2>✏️编辑试题</h2>
                <div class="form-group">
                    <label>试题ID：</label>
                    <input type="text" value="${q.id}" disabled style="background: #f5f5f5;">
                </div>
                <div class="form-group">
                    <label>试题内容：</label>
                    <textarea id="edit-question-content" rows="4">${q.content}</textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>试题类型：</label>
                        <select id="edit-question-type">
                            <option value="multiple_choice" ${q.question_type === 'multiple_choice' ? 'selected' : ''}>单选题</option>
                            <option value="true_false" ${q.question_type === 'true_false' ? 'selected' : ''}>判断题</option>
                            <option value="fill_blank" ${q.question_type === 'fill_blank' ? 'selected' : ''}>填空题</option>
                            <option value="short_answer" ${q.question_type === 'short_answer' ? 'selected' : ''}>简答题</option>
                            <option value="essay" ${q.question_type === 'essay' ? 'selected' : ''}>论述题</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>难度：</label>
                        <select id="edit-question-difficulty">
                            <option value="1" ${q.difficulty == 1 ? 'selected' : ''}>简单</option>
                            <option value="2" ${q.difficulty == 2 ? 'selected' : ''}>中等</option>
                            <option value="3" ${q.difficulty == 3 ? 'selected' : ''}>困难</option>
                            <option value="4" ${q.difficulty == 4 ? 'selected' : ''}>非常困难</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>学科：</label>
                        <input type="text" id="edit-question-subject" value="${q.subject}">
                    </div>
                    <div class="form-group">
                        <label>章节：</label>
                        <input type="text" id="edit-question-chapter" value="${q.chapter || ''}">
                    </div>
                </div>
                <div class="form-group">
                    <label>答案：</label>
                    <input type="text" id="edit-question-answer" value="${q.answer || ''}">
                </div>
                <div class="form-group">
                    <label>解析：</label>
                    <textarea id="edit-question-explanation" rows="3">${q.explanation || ''}</textarea>
                </div>
                <button onclick="saveQuestionEdit('${questionId}')" class="btn-success">💾保存修改</button>
                <button onclick="showQuestions()">↩️取消</button>
            `;
        } else {
            alert('❌获取试题详情失败');
        }
    } catch (error) {
        console.error('获取试题详情失败:', error);
        alert('❌获取试题详情失败');
    }
}

async function saveQuestionEdit(questionId) {
    const questionData = {
        content: document.getElementById('edit-question-content')?.value || '',
        question_type: document.getElementById('edit-question-type')?.value || '',
        subject: document.getElementById('edit-question-subject')?.value || '',
        chapter: document.getElementById('edit-question-chapter')?.value || '',
        difficulty: parseInt(document.getElementById('edit-question-difficulty')?.value) || 2,
        answer: document.getElementById('edit-question-answer')?.value || '',
        explanation: document.getElementById('edit-question-explanation')?.value || ''
    };

    try {
        const response = await fetch(`/api/questions/${questionId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(questionData)
        });

        const data = await response.json();

        if (response.ok) {
            alert('✅试题更新成功！');
            showQuestions();
        } else {
            alert(`❌更新失败: ${data.error}`);
        }
    } catch (error) {
        console.error('更新试题失败:', error);
        alert('❌更新试题失败，请重试');
    }
}

async function deleteQuestion(questionId) {
    if (!confirm('⚠️确定要删除这个试题吗？删除后无法恢复！')) {
        return;
    }

    try {
        const response = await fetch(`/api/questions/${questionId}`, {
            method: 'DELETE'
        });

        const data = await response.json();

        if (response.ok) {
            alert('✅试题删除成功！');
            searchQuestions();
        } else {
            alert(`❌删除失败: ${data.error}`);
        }
    } catch (error) {
        console.error('删除试题失败:', error);
        alert('❌删除试题失败，请重试');
    }
}

function getDifficultyText(difficulty) {
    // 确保输入值转换为数字
    const difficultyNum = parseInt(difficulty);
    const difficultyMap = {
        1: '😊简单',
        2: '😐中等', 
        3: '😰困难',
        4: '😱非常困难'
    };

    console.log(`难度值: ${difficulty} (原始), ${difficultyNum} (转换后)`); // 调试输出
    return difficultyMap[difficultyNum] || `❓难度${difficulty}`;
}

function getQuestionTypeText(type) {
    const typeMap = {
        'multiple_choice': '🔘单选题',
        'true_false': '✅判断题', 
        'fill_blank': '📝填空题',
        'short_answer': '💬简答题',
        'essay': '📄论述题'
    };
    return typeMap[type] || `❓${type}`;
}

async function loadAllUsers() {
    try {
        const response = await fetch('/api/users');
        const data = await response.json();

        let html = '<h3>📋用户列表</h3>';

        if (data.users && data.users.length > 0) {
            html += `<p>共有<strong>${data.users.length}</strong>个用户</p>`;
            for (const user of data.users) {
                html += `
                    <div class="user-item">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <h4>👤${user.username}</h4>
                                <p><strong>📧邮箱：</strong>${user.email}</p>
                                <p><strong>🎭角色：</strong><span class="role-badge role-${user.role}">${getRoleText(user.role)}</span></p>
                                <p><small>⏰注册时间：${new Date(user.created_time).toLocaleString()}</small></p>
                            </div>
                            <div>
                                ${user.role === 'admin' ? 
                                    '<button disabled class="btn-warning">🛡️管理员用户</button>' :
                                    (currentUser && currentUser.id === user.id) ?
                                        '<button disabled class="btn-info">👤当前用户</button>' :
                                        `<button onclick="deleteUser('${user.id}', '${user.username}')" class="btn-danger">🗑️删除用户</button>`
                                }
                            </div>
                        </div>
                    </div>
                `;
            }
        } else {
            html += '<div class="no-data">📭暂无用户数据。</div>';
        }

        document.getElementById('user-list').innerHTML = html;
    } catch (error) {
        document.getElementById('user-list').innerHTML = '<div class="alert alert-error">❌加载用户列表失败，请重试</div>';
        console.error('加载用户列表失败:', error);
    }
}

async function deleteUser(userId, username) {
    if (currentUser && currentUser.id === userId) {
        alert('🚫不能删除自己的账户！');
        return;
    }

    if (!confirm(`⚠️确定要删除用户"${username}"吗？删除后无法恢复！`)) {
        return;
    }

    try {
        const response = await fetch(`/api/users/${userId}`, {
            method: 'DELETE'
        });

        const data = await response.json();

        if (response.ok) {
            alert('✅用户删除成功！');
            loadAllUsers();
        } else {
            alert(`❌删除失败: ${data.error}`);
        }
    } catch (error) {
        console.error('删除用户失败:', error);
        alert('❌删除用户失败，请重试');
    }
}

async function loadStatistics() {
    try {
        const response = await fetch('/api/statistics/overview');
        const data = await response.json();

        if (response.ok) {
            let html = `
                <div class="stats-grid">
                    <div class="stats-card">
                        <h3>${data.total_questions || 0}</h3>
                        <p>📚总试题数</p>
                    </div>
                    <div class="stats-card">
                        <h3>${data.total_papers || 0}</h3>
                        <p>📄总试卷数</p>
                    </div>
            `;

            if (data.total_users !== undefined) {
                html += `
                    <div class="stats-card">
                        <h3>${data.total_users}</h3>
                        <p>👥总用户数</p>
                    </div>
                `;
            }

            html += `</div>`;

            // 学科分布统计
            if (data.questions_by_subject) {
                html += `
                    <div style="background: white; padding: 25px; border-radius: 12px; margin: 20px 0; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <h3>📊学科分布</h3>
                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                `;

                for (const [subject, count] of Object.entries(data.questions_by_subject)) {
                    html += `
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center;">
                            <div style="font-size: 24px; font-weight: bold; color: #007bff;">${count}</div>
                            <div style="color: #666;">${subject}</div>
                        </div>
                    `;
                }

                html += `</div></div>`;
            }

            // 修复：难度分布统计 - 按顺序显示并使用中文
            if (data.difficulty_distribution) {
                html += `
                    <div style="background: white; padding: 25px; border-radius: 12px; margin: 20px 0; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <h3>⭐难度分布</h3>
                        <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px;">
                `;

                // 修复：定义难度级别的固定顺序和中文显示
                const difficultyOrder = [
                    { 
                        key: '1', 
                        label: '😊简单', 
                        color: '#28a745',
                        fallbackKeys: [1, 'easy'] 
                    },
                    { 
                        key: '2', 
                        label: '😐中等', 
                        color: '#ffc107',
                        fallbackKeys: [2, 'medium'] 
                    },
                    { 
                        key: '3', 
                        label: '😰困难', 
                        color: '#fd7e14',
                        fallbackKeys: [3, 'hard'] 
                    },
                    { 
                        key: '4', 
                        label: '😱非常困难', 
                        color: '#dc3545',
                        fallbackKeys: [4, 'very_hard'] 
                    }
                ];

                console.log('原始难度分布数据:', data.difficulty_distribution); // 调试输出

                // 按照固定顺序显示难度分布
                for (const difficultyInfo of difficultyOrder) {
                    let count = 0;

                    // 尝试多种可能的键名匹配
                    const possibleKeys = [difficultyInfo.key, ...difficultyInfo.fallbackKeys];
                    for (const key of possibleKeys) {
                        if (data.difficulty_distribution[key] !== undefined) {
                            count = data.difficulty_distribution[key];
                            break;
                        }
                    }

                    console.log(`难度 ${difficultyInfo.label}: ${count}`); // 调试输出

                    html += `
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; border-left: 4px solid ${difficultyInfo.color};">
                            <div style="font-size: 24px; font-weight: bold; color: ${difficultyInfo.color};">${count}</div>
                            <div style="color: #666;">${difficultyInfo.label}</div>
                        </div>
                    `;
                }

                html += `</div></div>`;
            }

            // 活跃度统计
            if (data.recent_activities) {
                html += `
                    <div style="background: white; padding: 25px; border-radius: 12px; margin: 20px 0; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                        <h3>📈最近活动</h3>
                        <div id="activity-list">
                `;

                if (data.recent_activities.length > 0) {
                    for (const activity of data.recent_activities.slice(0, 10)) {
                        html += `
                            <div style="padding: 10px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between;">
                                <span>📝 ${activity.description}</span>
                                <small style="color: #666;">${new Date(activity.created_time).toLocaleString()}</small>
                            </div>
                        `;
                    }
                } else {
                    html += '<p style="text-align: center; color: #999;">暂无活动记录</p>';
                }

                html += `</div></div>`;
            }

            document.getElementById('main-content').innerHTML = `
                <h2>📊数据统计</h2>
                ${html}
            `;
        } else {
            document.getElementById('main-content').innerHTML = `
                <h2>📊数据统计</h2>
                <div class="alert alert-error">❌${data.error || '加载统计数据失败'}</div>
            `;
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
        document.getElementById('main-content').innerHTML = `
            <h2>📊数据统计</h2>
            <div class="alert alert-error">❌加载统计数据失败，请重试</div>
        `;
    }
}

function updateAdvancedSimilarity() {
    const slider = document.getElementById('advanced-similarity');
    const display = document.getElementById('advanced-similarity-value');

    if (slider && display) {
        display.textContent = Math.round(slider.value * 100) + '%';

        // 立即保存到增强设置
        const settings = loadEnhancedSettings();
        settings.similarityThreshold = parseFloat(slider.value);
        localStorage.setItem('enhancedSystemSettings', JSON.stringify(settings));

        // 同步到旧存储位置（兼容性）
        localStorage.setItem('aiSimilarityThreshold', slider.value);

        console.log('高级设置阈值更新为:', slider.value);
    }
}

function saveEnhancedSettings() {  
    const settings = {  
        similarityThreshold: parseFloat(document.getElementById('advanced-similarity')?.value || 0.8),  
        aiWeight: parseFloat(document.getElementById('ai-weight')?.value || 0.5),  
        aiComplexity: document.getElementById('ai-complexity')?.value || 'standard',  
        showAIPredictions: document.getElementById('show-ai-predictions')?.checked || false,  
        showDetailedComparison: document.getElementById('show-detailed-comparison')?.checked || false,  
        autoRefreshStats: document.getElementById('auto-refresh-stats')?.checked || false,  
        showConfidenceScores: document.getElementById('show-confidence-scores')?.checked || false,  
        notifyDuplicates: document.getElementById('notify-duplicates')?.checked || false,  
        notifyAnalysisComplete: document.getElementById('notify-analysis-complete')?.checked || false,  
        lastSaved: new Date().toISOString()  
    };  

    console.log('保存增强设置:', settings);  

    localStorage.setItem('enhancedSystemSettings', JSON.stringify(settings));  

    // 同时更新相似度阈值到旧的存储位置（兼容性）  
    localStorage.setItem('aiSimilarityThreshold', settings.similarityThreshold.toString());  

    // 同步更新基础设置界面  
    const basicSlider = document.getElementById('similarity-threshold');  
    const basicDisplay = document.getElementById('threshold-value');  
    if (basicSlider) {  
        basicSlider.value = settings.similarityThreshold;  
    }  
    if (basicDisplay) {  
        basicDisplay.textContent = Math.round(settings.similarityThreshold * 100) + '%';  
    }  

    // 应用设置  
    applyEnhancedSettings(settings);  

    console.log('相似度阈值已更新为:', settings.similarityThreshold);  
}

function loadEnhancedSettings() {
    const defaultSettings = {
        similarityThreshold: 0.8,
        aiWeight: 0.5,
        aiComplexity: 'standard',
        showAIPredictions: true,
        showDetailedComparison: true,
        autoRefreshStats: false,
        showConfidenceScores: false,
        notifyDuplicates: true,
        notifyAnalysisComplete: true
    };

    try {
        const saved = localStorage.getItem('enhancedSystemSettings');
        if (saved) {
            return { ...defaultSettings, ...JSON.parse(saved) };
        }
    } catch (error) {
        console.warn('加载设置失败，使用默认设置:', error);
    }

    return defaultSettings;
}

// 应用设置
function applyEnhancedSettings(settings) {
    // 应用自动刷新
    if (settings.autoRefreshStats) {
        startAutoRefresh();
    } else {
        stopAutoRefresh();
    }

    // 应用其他设置
    window.enhancedSettings = settings;
}

// 自动刷新功能
let autoRefreshInterval = null;

function startAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
    }

    autoRefreshInterval = setInterval(() => {
        // 如果当前在统计页面，自动刷新数据
        const currentPage = document.getElementById('enhanced-results');
        if (currentPage && currentPage.innerHTML.includes('系统综合数据统计分析')) {
            console.log('自动刷新统计数据...');
            showIntegratedStatistics();
        }
    }, 5 * 60 * 1000); // 5分钟
}

function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
    }
}

function showSettingsSavedNotification() {
    const notification = document.createElement('div');
    notification.innerHTML = `
        <div style="display: flex; align-items: center;">
            <span style="font-size: 18px; margin-right: 10px;">✅</span>
            <div>
                <div style="font-weight: bold;">设置已保存</div>
                <div style="font-size: 12px; opacity: 0.9;">所有配置已生效并保存到本地</div>
            </div>
        </div>
    `;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
        animation: slideInRight 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        min-width: 280px;
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.4s ease-in';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 400);
    }, 4000);
}

// 初始化增强功能设置
function initializeEnhancedFeatures() {
    // 加载并应用设置
    const settings = loadEnhancedSettings();
    applyEnhancedSettings(settings);

    // 初始化阈值显示
    initializeThresholdSettings();
}

// 在页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEnhancedFeatures();
});

function showAdvancedSettings() {
    // 加载已保存的设置
    const savedSettings = loadEnhancedSettings();

    showEnhancedModal('高级系统设置', `
        <div style="max-height: 500px; overflow-y: auto;">
            <div style="margin-bottom: 25px;">
                <h5 style="color: #333; margin-bottom: 15px; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">🤖</span>
                    AI分析参数
                </h5>

                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-size: 14px; margin-bottom: 8px; font-weight: 500;">相似度检测阈值</label>
                    <input type="range" id="advanced-similarity" min="0.5" max="1.0" step="0.05" value="${savedSettings.similarityThreshold}" 
                           style="width: 100%; margin-bottom: 8px;" onchange="updateAdvancedSimilarity()">
                    <div style="text-align: center; font-size: 12px; color: #666;">
                        当前: <span id="advanced-similarity-value">${Math.round(savedSettings.similarityThreshold * 100)}%</span>
                    </div>
                    <div style="font-size: 12px; color: #999; margin-top: 4px;">
                        💡 调整后立即生效，影响查重检测的敏感度
                    </div>
                </div>

                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-size: 14px; margin-bottom: 8px; font-weight: 500;">AI难度分析权重</label>
                    <select id="ai-weight" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="0.3" ${savedSettings.aiWeight == 0.3 ? 'selected' : ''}>保守模式 (30%) - 更信任人工判断</option>
                        <option value="0.5" ${savedSettings.aiWeight == 0.5 ? 'selected' : ''}>平衡模式 (50%) - 均衡参考</option>
                        <option value="0.7" ${savedSettings.aiWeight == 0.7 ? 'selected' : ''}>激进模式 (70%) - 更信任AI判断</option>
                    </select>
                </div>

                <div style="margin-bottom: 20px;">
                    <label style="display: block; font-size: 14px; margin-bottom: 8px; font-weight: 500;">AI分析复杂度</label>
                    <select id="ai-complexity" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="simple" ${savedSettings.aiComplexity === 'simple' ? 'selected' : ''}>简单模式 - 基础词汇分析</option>
                        <option value="standard" ${savedSettings.aiComplexity === 'standard' ? 'selected' : ''}>标准模式 - 综合特征分析</option>
                        <option value="advanced" ${savedSettings.aiComplexity === 'advanced' ? 'selected' : ''}>高级模式 - 深度语义分析</option>
                    </select>
                </div>
            </div>

            <div style="margin-bottom: 25px;">
                <h5 style="color: #333; margin-bottom: 15px; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">📊</span>
                    统计显示偏好
                </h5>

                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="show-ai-predictions" ${savedSettings.showAIPredictions ? 'checked' : ''} style="margin-right: 10px;">
                        <span style="font-size: 14px;">显示AI难度预测对比</span>
                    </label>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="show-detailed-comparison" ${savedSettings.showDetailedComparison ? 'checked' : ''} style="margin-right: 10px;">
                        <span style="font-size: 14px;">显示详细差异分析</span>
                    </label>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="auto-refresh-stats" ${savedSettings.autoRefreshStats ? 'checked' : ''} style="margin-right: 10px;">
                        <span style="font-size: 14px;">自动刷新统计数据 (每5分钟)</span>
                    </label>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="show-confidence-scores" ${savedSettings.showConfidenceScores ? 'checked' : ''} style="margin-right: 10px;">
                        <span style="font-size: 14px;">显示AI置信度分数</span>
                    </label>
                </div>
            </div>

            <div style="margin-bottom: 25px;">
                <h5 style="color: #333; margin-bottom: 15px; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">🔔</span>
                    通知设置
                </h5>

                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="notify-duplicates" ${savedSettings.notifyDuplicates ? 'checked' : ''} style="margin-right: 10px;">
                        <span style="font-size: 14px;">发现重复试题时通知</span>
                    </label>
                </div>

                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" id="notify-analysis-complete" ${savedSettings.notifyAnalysisComplete ? 'checked' : ''} style="margin-right: 10px;">
                        <span style="font-size: 14px;">AI分析完成时通知</span>
                    </label>
                </div>
            </div>

            <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                <p style="margin: 0; color: #1976d2; font-size: 14px; display: flex; align-items: center;">
                    <span style="font-size: 16px; margin-right: 8px;">💡</span>
                    这些设置将实时生效并自动保存到本地存储中。刷新页面后设置仍然有效。
                </p>
            </div>
        </div>
    `, function() {
        // 保存所有设置
        saveEnhancedSettings();
        showSettingsSavedNotification();
        closeEnhancedModal();
    });
}

function showEnhancedFeatures() {
    if (!currentUser) {
        alert('请先登录');
        return;
    }

    if (currentUser.role === 'assistant') {
        document.getElementById('main-content').innerHTML = `
            <h2>🚀系统增强功能</h2>
            <div class="permission-denied">
                ⚠️您当前是助教角色，没有权限使用增强功能
            </div>
        `;
        return;
    }

    document.getElementById('main-content').innerHTML = `
        <h2>🚀系统增强功能中心</h2>
        <p style="color: #666; margin-bottom: 30px;">集成智能查重、AI难度分析、考察统计等高级功能</p>

        <!-- 功能卡片网格 -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px;">

            <!-- 1. 智能试题分析 -->
            <div class="feature-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px; padding: 25px; box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3); transition: all 0.3s ease;">
                <div style="display: flex; align-items: center; margin-bottom: 15px;">
                    <span style="font-size: 28px; margin-right: 15px;">🤖</span>
                    <h3 style="margin: 0; color: white;">智能试题分析</h3>
                </div>
                <p style="color: rgba(255,255,255,0.9); margin-bottom: 20px;">AI驱动的试题难度分析与查重检测</p>
                <div style="display: flex; gap: 10px;">
                    <button onclick="showAIDifficultyAnalysis()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; flex: 1; font-size: 13px; backdrop-filter: blur(10px);">
                        🧠 AI难度分析
                    </button>
                    <button onclick="startBatchSimilarityCheck()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; flex: 1; font-size: 13px; backdrop-filter: blur(10px);">
                        🔍 智能查重
                    </button>
                </div>
                <div id="ai-analysis-status" style="margin-top: 15px; font-size: 12px; color: rgba(255,255,255,0.8);">
                    点击按钮开始AI智能分析
                </div>
            </div>

            <!-- 2. 综合数据统计 (整合原数据统计功能) -->
            <div class="feature-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; border-radius: 15px; padding: 25px; box-shadow: 0 8px 25px rgba(245, 87, 108, 0.3); transition: all 0.3s ease;">
                <div style="display: flex; align-items: center; margin-bottom: 15px;">
                    <span style="font-size: 28px; margin-right: 15px;">📊</span>
                    <h3 style="margin: 0; color: white;">数据统计中心</h3>
                </div>
                <p style="color: rgba(255,255,255,0.9); margin-bottom: 20px;">全面的系统数据分析与统计报告</p>
                <div style="display: flex; gap: 10px;">
                    <button onclick="showIntegratedStatistics()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; flex: 1; font-size: 13px; backdrop-filter: blur(10px);">
                        📋 综合统计
                    </button>
                    <button onclick="showUsageTrends()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; flex: 1; font-size: 13px; backdrop-filter: blur(10px);">
                        📈 使用趋势
                    </button>
                </div>
                <div id="stats-status" style="margin-top: 15px; font-size: 12px; color: rgba(255,255,255,0.8);">
                    数据统计功能已整合至此
                </div>
            </div>

            <!-- 3. 考察管理系统 -->
            <div class="feature-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; border-radius: 15px; padding: 25px; box-shadow: 0 8px 25px rgba(79, 172, 254, 0.3); transition: all 0.3s ease;">
                <div style="display: flex; align-items: center; margin-bottom: 15px;">
                    <span style="font-size: 28px; margin-right: 15px;">📚</span>
                    <h3 style="margin: 0; color: white;">考察管理系统</h3>
                </div>
                <p style="color: rgba(255,255,255,0.9); margin-bottom: 20px;">试题考察记录追踪与频次分析</p>
                <div style="display: flex; gap: 10px;">
                    <button onclick="showExamFrequencyPanel()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; flex: 1; font-size: 13px; backdrop-filter: blur(10px);">
                        📊 频次统计
                    </button>
                    <button onclick="showExamRecordManager()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; flex: 1; font-size: 13px; backdrop-filter: blur(10px);">
                        📝 记录管理
                    </button>
                </div>
                <div id="exam-status" style="margin-top: 15px; font-size: 12px; color: rgba(255,255,255,0.8);">
                    管理试题使用与考察情况
                </div>
            </div>

            <!-- 4. 系统配置中心 -->
            <div class="feature-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white; border-radius: 15px; padding: 25px; box-shadow: 0 8px 25px rgba(250, 112, 154, 0.3); transition: all 0.3s ease;">
                <div style="display: flex; align-items: center; margin-bottom: 15px;">
                    <span style="font-size: 28px; margin-right: 15px;">⚙️</span>
                    <h3 style="margin: 0; color: white;">系统配置中心</h3>
                </div>
                <p style="color: rgba(255,255,255,0.9); margin-bottom: 15px;">智能算法参数调优与系统设置</p>
                
                <button onclick="showAdvancedSettings()" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 15px; border-radius: 20px; cursor: pointer; width: 100%; font-size: 13px; backdrop-filter: blur(10px);">
                    🔧 高级设置
                </button>
            </div>
        </div>

        <!-- 核心数据概览仪表板 -->
        <div style="background: white; border-radius: 15px; padding: 25px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); margin-bottom: 30px;">
            <h3 style="margin: 0 0 20px 0; color: #333; display: flex; align-items: center;">
                <span style="font-size: 24px; margin-right: 10px;">🎯</span>
                系统核心数据仪表板
            </h3>
            <div id="dashboard-overview" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px;">
                <div style="text-align: center; background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 20px; border-radius: 12px;">
                    <div style="font-size: 32px; font-weight: bold;" id="dash-questions">-</div>
                    <div style="font-size: 14px; opacity: 0.9;">📚 总试题数</div>
                </div>
                <div style="text-align: center; background: linear-gradient(135deg, #f093fb, #f5576c); color: white; padding: 20px; border-radius: 12px;">
                    <div style="font-size: 32px; font-weight: bold;" id="dash-papers">-</div>
                    <div style="font-size: 14px; opacity: 0.9;">📄 总试卷数</div>
                </div>
                <div style="text-align: center; background: linear-gradient(135deg, #4facfe, #00f2fe); color: white; padding: 20px; border-radius: 12px;">
                    <div style="font-size: 32px; font-weight: bold;" id="dash-users">-</div>
                    <div style="font-size: 14px; opacity: 0.9;">👥 总用户数</div>
                </div>
                <div style="text-align: center; background: linear-gradient(135deg, #43e97b, #38f9d7); color: white; padding: 20px; border-radius: 12px;">
                    <div style="font-size: 32px; font-weight: bold;" id="dash-exams">-</div>
                    <div style="font-size: 14px; opacity: 0.9;">📊 考察记录</div>
                </div>
            </div>
        </div>

        <!-- 详细结果显示区域 -->
        <div id="enhanced-results" style="background: white; border-radius: 15px; padding: 25px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); min-height: 400px;">
            <div style="text-align: center; padding: 80px 20px; color: #999;">
                <span style="font-size: 64px; display: block; margin-bottom: 20px;">🚀</span>
                <h4 style="margin: 0 0 10px 0; color: #666;">增强功能中心</h4>
                <p style="font-size: 16px; margin: 0;">选择上方功能模块开始使用高级功能</p>
            </div>
        </div>
    `;

    // 添加动画效果
    const style = document.createElement('style');
    style.textContent = `
        .feature-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 15px 35px rgba(0,0,0,0.2) !important;
        }
        .feature-card {
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) !important;
        }
    `;
    document.head.appendChild(style);

    // 加载仪表板数据
    loadDashboardData();

}

async function showAIDifficultyAnalysis() {
    const statusDiv = document.getElementById('ai-analysis-status');
    const resultsDiv = document.getElementById('enhanced-results');

    statusDiv.textContent = '🤖 正在进行AI难度分析...';

    try {
        // 同时获取基础统计和AI分析数据
        const [statsResponse, aiResponse] = await Promise.all([
            fetch('/api/statistics/comprehensive'),
            fetch('/api/questions/search') // 获取所有试题进行AI分析
        ]);

        if (statsResponse.ok && aiResponse.ok) {
            const statsData = await statsResponse.json();
            const questionsData = await aiResponse.json();

            displayDifficultyComparison(statsData, questionsData.questions, statusDiv, resultsDiv);
        } else {
            throw new Error('获取数据失败');
        }
    } catch (error) {
        statusDiv.textContent = '❌ AI分析失败: ' + error.message;
    }
}

function displayDifficultyComparison(statsData, questions, statusDiv, resultsDiv) {
    statusDiv.textContent = '✅ AI难度分析完成';

    // 计算AI预测难度分布
    const aiDifficultyDist = { 1: 0, 2: 0, 3: 0, 4: 0 };
    const comparisonData = [];

    questions.forEach(question => {
        const aiDifficulty = predictAIDifficulty(question);
        aiDifficultyDist[aiDifficulty]++;

        comparisonData.push({
            id: question.id,
            content: question.content.substring(0, 150),
            subject: question.subject,
            manualDifficulty: question.difficulty,
            aiDifficulty: aiDifficulty,
            difference: Math.abs(question.difficulty - aiDifficulty)
        });
    });

    const manualDist = statsData.difficulty_distribution || {};
    const total = questions.length;

    let html = `
        <h3 style="margin-bottom: 25px; color: #333; display: flex; align-items: center;">
            <span style="font-size: 24px; margin-right: 10px;">🤖</span>
            AI智能难度分析 vs 人工设定对比
        </h3>

        <!-- 对比概览 -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 30px;">
            <!-- 人工设定难度 -->
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px; padding: 25px;">
                <h4 style="margin: 0 0 20px 0; display: flex; align-items: center;">
                    <span style="font-size: 20px; margin-right: 8px;">👨‍🏫</span>
                    人工设定难度分布
                </h4>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${manualDist['1'] || 0}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😊 简单</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round((manualDist['1'] || 0) / total * 100) : 0}%</div>
                    </div>
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${manualDist['2'] || 0}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😐 中等</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round((manualDist['2'] || 0) / total * 100) : 0}%</div>
                    </div>
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${manualDist['3'] || 0}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😰 困难</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round((manualDist['3'] || 0) / total * 100) : 0}%</div>
                    </div>
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${manualDist['4'] || 0}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😱 非常困难</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round((manualDist['4'] || 0) / total * 100) : 0}%</div>
                    </div>
                </div>
            </div>

            <!-- AI预测难度 -->
            <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; border-radius: 15px; padding: 25px;">
                <h4 style="margin: 0 0 20px 0; display: flex; align-items: center;">
                    <span style="font-size: 20px; margin-right: 8px;">🤖</span>
                    AI预测难度分布
                </h4>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${aiDifficultyDist[1]}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😊 简单</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round(aiDifficultyDist[1] / total * 100) : 0}%</div>
                    </div>
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${aiDifficultyDist[2]}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😐 中等</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round(aiDifficultyDist[2] / total * 100) : 0}%</div>
                    </div>
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${aiDifficultyDist[3]}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😰 困难</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round(aiDifficultyDist[3] / total * 100) : 0}%</div>
                    </div>
                    <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                        <div style="font-size: 24px; font-weight: bold;">${aiDifficultyDist[4]}</div>
                        <div style="font-size: 12px; opacity: 0.9;">😱 非常困难</div>
                        <div style="font-size: 10px; opacity: 0.7;">${total > 0 ? Math.round(aiDifficultyDist[4] / total * 100) : 0}%</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 一致性分析 -->
        <div style="background: #f8f9fa; border-radius: 15px; padding: 25px; margin-bottom: 25px;">
            <h4 style="margin: 0 0 20px 0; color: #495057; display: flex; align-items: center;">
                <span style="font-size: 20px; margin-right: 8px;">📊</span>
                AI vs 人工难度一致性分析
            </h4>

            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 20px;">
                <div style="text-align: center; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div style="font-size: 28px; font-weight: bold; color: #28a745;">${comparisonData.filter(d => d.difference === 0).length}</div>
                    <div style="color: #666; font-size: 14px;">完全一致</div>
                    <div style="color: #999; font-size: 12px;">${total > 0 ? Math.round(comparisonData.filter(d => d.difference === 0).length / total * 100) : 0}%</div>
                </div>
                <div style="text-align: center; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div style="font-size: 28px; font-weight: bold; color: #ffc107;">${comparisonData.filter(d => d.difference === 1).length}</div>
                    <div style="color: #666; font-size: 14px;">相差1级</div>
                    <div style="color: #999; font-size: 12px;">${total > 0 ? Math.round(comparisonData.filter(d => d.difference === 1).length / total * 100) : 0}%</div>
                </div>
                <div style="text-align: center; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div style="font-size: 28px; font-weight: bold; color: #dc3545;">${comparisonData.filter(d => d.difference >= 2).length}</div>
                    <div style="color: #666; font-size: 14px;">相差2级+</div>
                    <div style="color: #999; font-size: 12px;">${total > 0 ? Math.round(comparisonData.filter(d => d.difference >= 2).length / total * 100) : 0}%</div>
                </div>
                <div style="text-align: center; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div style="font-size: 28px; font-weight: bold; color: #007bff;">${total > 0 ? (comparisonData.reduce((sum, d) => sum + d.difference, 0) / total).toFixed(2) : 0}</div>
                    <div style="color: #666; font-size: 14px;">平均差异</div>
                    <div style="color: #999; font-size: 12px;">难度级别</div>
                </div>
            </div>
        </div>

        <!-- 完整差异详情列表 -->
        <div style="background: white; border-radius: 15px; padding: 25px;">
            <h4 style="margin: 0 0 20px 0; color: #495057; display: flex; align-items: center; justify-content: space-between;">
                <span style="display: flex; align-items: center;">
                    <span style="font-size: 20px; margin-right: 8px;">🔍</span>
                    完整详细差异分析
                </span>
                <span style="font-size: 14px; color: #999;">总计 ${total} 道试题</span>
            </h4>

            <!-- 筛选控件 -->
            <div style="margin-bottom: 20px; display: flex; gap: 15px; align-items: center; padding: 15px; background: #f8f9fa; border-radius: 10px;">
                <label style="display: flex; align-items: center; gap: 5px;">
                    筛选差异级别：
                    <select id="diff-filter" onchange="filterDifferenceResults()" style="padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="all">所有</option>
                        <option value="0">完全一致</option>
                        <option value="1">相差1级</option>
                        <option value="2+">相差2级以上</option>
                    </select>
                </label>
                <label style="display: flex; align-items: center; gap: 5px;">
                    排序方式：
                    <select id="sort-order" onchange="filterDifferenceResults()" style="padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="diff-desc">差异大到小</option>
                        <option value="diff-asc">差异小到大</option>
                        <option value="manual-asc">人工难度↑</option>
                        <option value="ai-asc">AI难度↑</option>
                    </select>
                </label>
            </div>

            <div id="comparison-results" style="max-height: 600px; overflow-y: auto;">
    `;

    // 显示所有试题对比结果
    comparisonData
        .sort((a, b) => b.difference - a.difference)
        .forEach((item, index) => {
            const diffColor = item.difference === 0 ? '#28a745' : 
                             item.difference === 1 ? '#ffc107' : '#dc3545';
            html += `
                <div class="comparison-item" data-difference="${item.difference}" style="border: 1px solid #e9ecef; padding: 15px; margin-bottom: 10px; border-radius: 10px; background: ${item.difference === 0 ? '#f8fff8' : item.difference >= 2 ? '#fff5f5' : '#fffaf0'};">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <div style="flex: 1;">
                            <span style="font-weight: bold; color: #333;">试题 #${item.id}</span>
                            <span style="color: #666; font-size: 14px; margin-left: 10px;">${item.subject}</span>
                        </div>
                        <div style="display: flex; gap: 15px; align-items: center;">
                            <span style="background: #667eea; color: white; padding: 4px 8px; border-radius: 15px; font-size: 12px;">
                                👨‍🏫 人工: ${['', '简单', '中等', '困难', '非常困难'][item.manualDifficulty]}
                            </span>
                            <span style="background: #f093fb; color: white; padding: 4px 8px; border-radius: 15px; font-size: 12px;">
                                🤖 AI: ${['', '简单', '中等', '困难', '非常困难'][item.aiDifficulty]}
                            </span>
                            <span style="background: ${diffColor}; color: white; padding: 4px 8px; border-radius: 15px; font-size: 12px;">
                                差异: ${item.difference}级
                            </span>
                        </div>
                    </div>
                    <div style="color: #666; font-size: 14px; line-height: 1.4;">
                        ${item.content}${item.content.length >= 150 ? '...' : ''}
                    </div>
                </div>
            `;
        });

    html += `
            </div>
        </div>
    `;

    resultsDiv.innerHTML = html;

    // 存储数据供筛选使用
    window.comparisonData = comparisonData;
}

function filterDifferenceResults() {
    const diffFilter = document.getElementById('diff-filter').value;
    const sortOrder = document.getElementById('sort-order').value;
    let filteredData = [...window.comparisonData];

    // 筛选
    if (diffFilter !== 'all') {
        if (diffFilter === '2+') {
            filteredData = filteredData.filter(item => item.difference >= 2);
        } else {
            filteredData = filteredData.filter(item => item.difference === parseInt(diffFilter));
        }
    }

    // 排序
    switch(sortOrder) {
        case 'diff-desc':
            filteredData.sort((a, b) => b.difference - a.difference);
            break;
        case 'diff-asc':
            filteredData.sort((a, b) => a.difference - b.difference);
            break;
        case 'manual-asc':
            filteredData.sort((a, b) => a.manualDifficulty - b.manualDifficulty);
            break;
        case 'ai-asc':
            filteredData.sort((a, b) => a.aiDifficulty - b.aiDifficulty);
            break;
    }

    // 重新渲染结果
    const resultsContainer = document.getElementById('comparison-results');
    let html = '';

    filteredData.forEach((item, index) => {
        const diffColor = item.difference === 0 ? '#28a745' : 
                         item.difference === 1 ? '#ffc107' : '#dc3545';
        html += `
            <div class="comparison-item" style="border: 1px solid #e9ecef; padding: 15px; margin-bottom: 10px; border-radius: 10px; background: ${item.difference === 0 ? '#f8fff8' : item.difference >= 2 ? '#fff5f5' : '#fffaf0'};">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <div style="flex: 1;">
                        <span style="font-weight: bold; color: #333;">试题 #${item.id}</span>
                        <span style="color: #666; font-size: 14px; margin-left: 10px;">${item.subject}</span>
                    </div>
                    <div style="display: flex; gap: 15px; align-items: center;">
                        <span style="background: #667eea; color: white; padding: 4px 8px; border-radius: 15px; font-size: 12px;">
                            👨‍🏫 人工: ${['', '简单', '中等', '困难', '非常困难'][item.manualDifficulty]}
                        </span>
                        <span style="background: #f093fb; color: white; padding: 4px 8px; border-radius: 15px; font-size: 12px;">
                            🤖 AI: ${['', '简单', '中等', '困难', '非常困难'][item.aiDifficulty]}
                        </span>
                        <span style="background: ${diffColor}; color: white; padding: 4px 8px; border-radius: 15px; font-size: 12px;">
                            差异: ${item.difference}级
                        </span>
                    </div>
                </div>
                <div style="color: #666; font-size: 14px; line-height: 1.4;">
                    ${item.content}${item.content.length >= 150 ? '...' : ''}
                </div>
            </div>
        `;
    });

    resultsContainer.innerHTML = html;
}

// AI难度预测算法（简化版，实际应该调用后端AI服务）
function predictAIDifficulty(question) {
    const content = question.content.toLowerCase();
    let score = 1.0; // 从简单开始评估

    // 文本长度因子
    if (content.length > 100) score += 0.3;
    else if (content.length > 200) score += 0.6;
    else if (content.length > 400) score += 1.0;

    // 复杂词汇检测
    const easyWords = ['是', '什么', '哪个', '选择', '判断', '简单', '基本', '容易'];
    const mediumWords = ['计算', '分析', '比较', '解释', '应用', '理解'];
    const hardWords = ['积分', '微分', '量子', '相对论', '矩阵', '线性代数', '概率论', '统计学', '算法', '复杂', '高级'];
    const veryHardWords = ['拓扑', '群论', '泛函', '微积分', '偏微分', '复变函数', '实变函数'];

    let easyCount = 0, mediumCount = 0, hardCount = 0, veryHardCount = 0;

    easyWords.forEach(word => {
        if (content.includes(word)) easyCount++;
    });
    mediumWords.forEach(word => {
        if (content.includes(word)) mediumCount++;
    });
    hardWords.forEach(word => {
        if (content.includes(word)) hardCount++;
    });
    veryHardWords.forEach(word => {
        if (content.includes(word)) veryHardCount++;
    });

    // 根据词汇分布调整分数
    if (easyCount > 2) score -= 0.3;
    if (mediumCount > 1) score += 0.4;
    if (hardCount > 0) score += 0.8 * hardCount;
    if (veryHardCount > 0) score += 1.2 * veryHardCount;

    // 数学运算难度分级 - 重新排序
    // 1. 最难：乘方运算
    if (content.includes('^') || content.includes('乘方') || content.includes('平方') || content.includes('立方') || /\d+\^\d+|x\^2/.test(content)) {
        score += 1.5; // 乘方最难
    }
    // 2. 次难：乘法和除法
    else if (content.includes('乘法') || content.includes('×') || content.includes('*') || 
             content.includes('除法') || content.includes('÷') || content.includes('/')) {
        score += 0.8; // 乘除法次难
    }
    // 3. 最简单：加法和减法
    else if (content.includes('加法') || content.includes('+') || 
             content.includes('减法') || content.includes('-')) {
        // 检查是否是简单的加减法（如 1+3, 5-2）
        const simpleArithmetic = /^\s*\d+\s*[+\-]\s*\d+\s*$/;
        if (simpleArithmetic.test(content.trim())) {
            score = 1; // 强制设为最简单
        } else {
            score += 0.2; // 复杂的加减法稍微增加难度
        }
    }

    // 高级数学符号检测 - 最难级别
    if (/[∫∑∏√π∞≠≤≥±∂∇]/.test(content)) score += 1.2;
    if (/\b(sin|cos|tan|log|ln|exp|lim|∂|∞)\b/.test(content)) score += 1.0;

    // 题目类型影响
    if (question.question_type === 'essay') score += 0.7;
    else if (question.question_type === 'calculation') score += 0.4;
    else if (question.question_type === 'multiple_choice') score -= 0.2;
    else if (question.question_type === 'true_false') score -= 0.4;

    // 转换为1-4的整数
    const finalScore = Math.max(1, Math.min(4, Math.round(score)));
    return finalScore;
}


// 3. 整合统计功能
async function showIntegratedStatistics() {
    const statusDiv = document.getElementById('stats-status');
    const resultsDiv = document.getElementById('enhanced-results');

    statusDiv.textContent = '📊 正在加载综合统计数据...';
    statusDiv.style.color = '#f093fb';

    try {
        // 修正API调用路径
        const response = await fetch('/api/statistics/comprehensive');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();

        // 添加调试信息
        console.log('统计数据:', data);

        displayIntegratedStatistics(data, statusDiv, resultsDiv);

    } catch (error) {
        console.error('统计数据加载失败:', error);
        statusDiv.textContent = '❌ 加载失败: ' + error.message;
        statusDiv.style.color = '#dc3545';

        // 显示备用的模拟数据
        displayFallbackStatistics(resultsDiv);
    }
}

function displayIntegratedStatistics(data, statusDiv, resultsDiv) {
    statusDiv.textContent = '✅ 统计数据加载完成';
    statusDiv.style.color = '#28a745';

    let html = `
        <h3 style="margin-bottom: 25px; color: #333; display: flex; align-items: center;">
            <span style="font-size: 24px; margin-right: 10px;">📊</span>
            系统综合数据统计分析
        </h3>

        <!-- 核心指标卡片 -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 15px; text-align: center;">
                <div style="font-size: 36px; font-weight: bold; margin-bottom: 10px;">${data.total_questions || 0}</div>
                <div style="font-size: 16px; opacity: 0.9;">📚 试题总数</div>
                <div style="font-size: 12px; opacity: 0.7; margin-top: 5px;">系统核心资源</div>
            </div>
            <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 25px; border-radius: 15px; text-align: center;">
                <div style="font-size: 36px; font-weight: bold; margin-bottom: 10px;">${data.total_papers || 0}</div>
                <div style="font-size: 16px; opacity: 0.9;">📄 试卷总数</div>
                <div style="font-size: 12px; opacity: 0.7; margin-top: 5px;">组卷成果</div>
            </div>
            <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 25px; border-radius: 15px; text-align: center;">
                <div style="font-size: 36px; font-weight: bold; margin-bottom: 10px;">${data.total_users || 0}</div>
                <div style="font-size: 16px; opacity: 0.9;">👥 用户总数</div>
                <div style="font-size: 12px; opacity: 0.7; margin-top: 5px;">活跃用户</div>
            </div>
        </div>

        <!-- 学科与难度分析 -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 30px;">
            <!-- 学科分布 -->
            <div style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
                <h4 style="margin: 0 0 20px 0; color: #495057; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">📚</span>
                    学科资源分布
                </h4>
    `;

    // 处理学科分布数据
    if (data.subject_distribution && data.subject_distribution.length > 0) {
        data.subject_distribution.forEach((subject, index) => {
            const percentage = data.total_questions > 0 ? Math.round((subject.count / data.total_questions) * 100) : 0;
            html += `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                    <div>
                        <span style="font-weight: 500; color: #333;">${subject.subject}</span>
                        <span style="color: #666; font-size: 12px; margin-left: 10px;">${percentage}%</span>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-weight: bold; color: #007bff;">${subject.count}</div>
                        <div style="font-size: 11px; color: #999;">${subject.total_usage || 0}次使用</div>
                    </div>
                </div>
            `;
        });
    } else {
        html += '<p style="color: #999; text-align: center; padding: 20px;">暂无学科数据</p>';
    }

    html += `
            </div>

            <!-- 难度分布 -->
            <div style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
                <h4 style="margin: 0 0 20px 0; color: #495057; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">⭐</span>
                    难度级别分布
                </h4>
    `;

    // 处理难度分布数据
    const difficultyDist = data.difficulty_distribution || {};
    const difficultyLevels = [
        { key: '1', label: '😊 简单', color: '#28a745' },
        { key: '2', label: '😐 中等', color: '#ffc107' },
        { key: '3', label: '😰 困难', color: '#fd7e14' },
        { key: '4', label: '😱 非常困难', color: '#dc3545' }
    ];

    difficultyLevels.forEach(level => {
        const count = difficultyDist[level.key] || 0;
        const percentage = data.total_questions > 0 ? Math.round((count / data.total_questions) * 100) : 0;
        html += `
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                <div>
                    <span style="font-weight: 500; color: #333;">${level.label}</span>
                    <span style="color: #666; font-size: 12px; margin-left: 10px;">${percentage}%</span>
                </div>
                <div style="text-align: right;">
                    <div style="font-weight: bold; color: ${level.color};">${count}</div>
                    <div style="font-size: 11px; color: #999;">道题目</div>
                </div>
            </div>
        `;
    });

    html += `
            </div>
        </div>
    `;

    resultsDiv.innerHTML = html;
}

async function showUsageTrends() {
    const statusDiv = document.getElementById('stats-status');
    const resultsDiv = document.getElementById('enhanced-results');

    statusDiv.textContent = '📈 正在分析使用趋势...';
    statusDiv.style.color = '#f093fb';

    // 模拟趋势数据（实际应该从后端获取）
    const trendData = generateMockTrendData();

    displayUsageTrends(trendData, statusDiv, resultsDiv);
}

function generateMockTrendData() {
    const days = 30;
    const data = [];

    for (let i = days; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);

        data.push({
            date: date.toLocaleDateString(),
            questions_created: Math.floor(Math.random() * 10 + 2),
            papers_created: Math.floor(Math.random() * 5 + 1),
            user_logins: Math.floor(Math.random() * 20 + 5),
            ai_analyses: Math.floor(Math.random() * 15 + 3)
        });
    }

    return data;
}

function displayUsageTrends(data, statusDiv, resultsDiv) {
    statusDiv.textContent = '✅ 趋势分析完成';
    statusDiv.style.color = '#28a745';

    const recent7Days = data.slice(-7);
    const totalQuestions = recent7Days.reduce((sum, day) => sum + day.questions_created, 0);
    const totalPapers = recent7Days.reduce((sum, day) => sum + day.papers_created, 0);
    const avgLogins = Math.round(recent7Days.reduce((sum, day) => sum + day.user_logins, 0) / 7);

    let html = `
        <h3 style="margin-bottom: 25px; color: #333; display: flex; align-items: center;">
            <span style="font-size: 24px; margin-right: 10px;">📈</span>
            系统使用趋势分析
        </h3>

        <!-- 趋势概览 -->
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 15px; margin-bottom: 25px;">
            <h4 style="margin: 0 0 20px 0; text-align: center;">📊 近7天活动概览</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px;">
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">${totalQuestions}</div>
                    <div style="font-size: 14px; opacity: 0.9;">新增试题</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">${totalPapers}</div>
                    <div style="font-size: 14px; opacity: 0.9;">新增试卷</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">${avgLogins}</div>
                    <div style="font-size: 14px; opacity: 0.9;">日均登录</div>
                </div>
            </div>
        </div>

        <!-- 详细趋势图表 -->
        <div style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
            <h4 style="margin: 0 0 20px 0; color: #495057;">📈 30天活动趋势</h4>
            <div style="overflow-x: auto;">
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #f8f9fa;">
                            <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6;">日期</th>
                            <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">📚 新增试题</th>
                            <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">📄 新增试卷</th>
                            <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">👥 用户登录</th>
                            <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">🤖 AI分析</th>
                        </tr>
                    </thead>
                    <tbody>
    `;

    data.slice(-10).forEach((day, index) => {
        html += `
                        <tr style="border-bottom: 1px solid #e9ecef; ${index % 2 === 0 ? 'background: #f8f9fa;' : ''}">
                            <td style="padding: 10px; font-weight: 500;">${day.date}</td>
                            <td style="padding: 10px; text-align: center;">
                                <span style="background: #e3f2fd; color: #1976d2; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                                    ${day.questions_created}
                                </span>
                            </td>
                            <td style="padding: 10px; text-align: center;">
                                <span style="background: #f3e5f5; color: #7b1fa2; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                                    ${day.papers_created}
                                </span>
                            </td>
                            <td style="padding: 10px; text-align: center;">
                                <span style="background: #e8f5e8; color: #2e7d32; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                                    ${day.user_logins}
                                </span>
                            </td>
                            <td style="padding: 10px; text-align: center;">
                                <span style="background: #fff3e0; color: #f57c00; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                                    ${day.ai_analyses}
                                </span>
                            </td>
                        </tr>
        `;
    });

    html += `
                    </tbody>
                </table>
            </div>
        </div>
    `;

    resultsDiv.innerHTML = html;
}


// 4. 考察记录管理器
function showExamRecordManager() {
    const resultsDiv = document.getElementById('enhanced-results');

    resultsDiv.innerHTML = `
        <h3 style="margin-bottom: 25px; color: #333; display: flex; align-items: center;">
            <span style="font-size: 24px; margin-right: 10px;">📚</span>
            考察记录管理中心
        </h3>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px;">
            <!-- 添加记录 -->
            <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 25px; border-radius: 15px;">
                <h4 style="margin: 0 0 20px 0; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">➕</span>
                    添加考察记录
                </h4>
                <div style="space-y: 15px;">
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-size: 14px; margin-bottom: 5px; opacity: 0.9;">试题ID</label>
                        <input type="text" id="record-question-id" placeholder="输入试题ID" 
                               style="width: 100%; padding: 10px; border: none; border-radius: 8px; background: rgba(255,255,255,0.2); color: white; backdrop-filter: blur(10px);">
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-size: 14px; margin-bottom: 5px; opacity: 0.9;">考试名称</label>
                        <input type="text" id="record-exam-name" placeholder="例如：期中考试" 
                               style="width: 100%; padding: 10px; border: none; border-radius: 8px; background: rgba(255,255,255,0.2); color: white; backdrop-filter: blur(10px);">
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-size: 14px; margin-bottom: 5px; opacity: 0.9;">考试日期</label>
                        <input type="date" id="record-exam-date" 
                               style="width: 100%; padding: 10px; border: none; border-radius: 8px; background: rgba(255,255,255,0.2); color: white; backdrop-filter: blur(10px);">
                    </div>
                    <button onclick="submitExamRecord(document.getElementById('record-question-id').value, document.getElementById('record-exam-name').value, document.getElementById('record-exam-date').value)" 
                            style="width: 100%; background: rgba(255,255,255,0.3); color: white; border: 1px solid rgba(255,255,255,0.5); padding: 12px; border-radius: 8px; cursor: pointer; backdrop-filter: blur(10px);">
                        ✅ 添加记录
                    </button>
                </div>
            </div>

            <!-- 查询记录 -->
            <div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white; padding: 25px; border-radius: 15px;">
                <h4 style="margin: 0 0 20px 0; display: flex; align-items: center;">
                    <span style="font-size: 18px; margin-right: 8px;">🔍</span>
                    查询考察记录
                </h4>
                <div style="space-y: 15px;">
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; font-size: 14px; margin-bottom: 5px; opacity: 0.9;">试题ID</label>
                        <input type="text" id="query-question-id" placeholder="输入试题ID查询历史" 
                               style="width: 100%; padding: 10px; border: none; border-radius: 8px; background: rgba(255,255,255,0.2); color: white; backdrop-filter: blur(10px);">
                    </div>
                    <button onclick="queryExamRecords(document.getElementById('query-question-id').value)" 
                            style="width: 100%; background: rgba(255,255,255,0.3); color: white; border: 1px solid rgba(255,255,255,0.5); padding: 12px; border-radius: 8px; cursor: pointer; backdrop-filter: blur(10px);">
                        🔍 查询记录
                    </button>
                    <div style="margin-top: 20px;">
                        <button onclick="showExamFrequencyPanel()" 
                                style="width: 100%; background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 10px; border-radius: 8px; cursor: pointer; backdrop-filter: blur(10px);">
                            📊 查看频次统计
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div id="exam-record-results" style="margin-top: 25px;">
            <!-- 动态结果显示区域 -->
        </div>
    `;
}

// 5. 加载仪表板数据
async function loadDashboardData() {
    try {
        const response = await fetch('/api/statistics/comprehensive');
        if (response.ok) {
            const data = await response.json();

            document.getElementById('dash-questions').textContent = data.total_questions || 0;
            document.getElementById('dash-papers').textContent = data.total_papers || 0;
            document.getElementById('dash-users').textContent = data.total_users || 0;
            document.getElementById('dash-exams').textContent = data.total_exams || 0;
        }
    } catch (error) {
        console.log('仪表板数据加载失败:', error);
    }
}

function showThresholdSavedTip() {
    // 创建提示消息
    const tip = document.createElement('div');
    tip.textContent = '✅ 阈值已保存';
    tip.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #28a745;
        color: white;
        padding: 8px 16px;
        border-radius: 6px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        animation: slideInRight 0.3s ease-out;
    `;

    // 添加动画样式
    if (!document.getElementById('tip-animations')) {
        const style = document.createElement('style');
        style.id = 'tip-animations';
        style.textContent = `
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    }

    document.body.appendChild(tip);

    // 3秒后自动移除
    setTimeout(() => {
        tip.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (tip.parentNode) {
                tip.parentNode.removeChild(tip);
            }
        }, 300);
    }, 3000);
}

// 更新阈值显示
function updateThresholdDisplay() {  
    const slider = document.getElementById('similarity-threshold');  
    const display = document.getElementById('threshold-value');  

    if (slider && display) {  
        const value = Math.round(slider.value * 100);  
        display.textContent = value + '%';  

        // 保存设置到本地存储  
        localStorage.setItem('aiSimilarityThreshold', slider.value);  

        // 同步更新到增强设置  
        try {  
            const settings = loadEnhancedSettings();  
            settings.similarityThreshold = parseFloat(slider.value);  
            settings.lastSaved = new Date().toISOString();  
            localStorage.setItem('enhancedSystemSettings', JSON.stringify(settings));  
            console.log('基础设置同步到增强设置:', slider.value);  
        } catch (error) {  
            console.warn('同步到增强设置失败:', error);  
        }  

        // 同步到高级设置界面（如果存在）  
        const advancedSlider = document.getElementById('advanced-similarity');  
        const advancedDisplay = document.getElementById('advanced-similarity-value');  
        if (advancedSlider) {  
            advancedSlider.value = slider.value;  
        }  
        if (advancedDisplay) {  
            advancedDisplay.textContent = value + '%';  
        }  

        // 显示设置已保存的提示  
        showThresholdSavedTip();  
    }  
}

function updateAdvancedSimilarity() {  
    const slider = document.getElementById('advanced-similarity');  
    const display = document.getElementById('advanced-similarity-value');  

    if (slider && display) {  
        const value = Math.round(slider.value * 100);  
        display.textContent = value + '%';  

        console.log('高级设置阈值更新为:', slider.value);  

        // 立即保存到增强设置  
        try {  
            const settings = loadEnhancedSettings();  
            settings.similarityThreshold = parseFloat(slider.value);  
            settings.lastSaved = new Date().toISOString();  
            localStorage.setItem('enhancedSystemSettings', JSON.stringify(settings));  
        } catch (error) {  
            console.warn('保存增强设置失败:', error);  
        }  

        // 同步更新到基础设置（兼容性）  
        localStorage.setItem('aiSimilarityThreshold', slider.value);  

        // 同步更新基础设置界面（如果存在）  
        const basicSlider = document.getElementById('similarity-threshold');  
        const basicDisplay = document.getElementById('threshold-value');  
        if (basicSlider) {  
            basicSlider.value = slider.value;  
        }  
        if (basicDisplay) {  
            basicDisplay.textContent = value + '%';  
        }  

        // 显示设置已保存的提示  
        showThresholdSavedTip();  
    }  
}

function calculateSimilarity(text1, text2) {
    const words1 = text1.toLowerCase().split(/\s+/);
    const words2 = text2.toLowerCase().split(/\s+/);

    const set1 = new Set(words1);
    const set2 = new Set(words2);

    const intersection = new Set([...set1].filter(x => set2.has(x)));
    const union = new Set([...set1, ...set2]);

    return intersection.size / union.size;
}

// 获取相似度阈值
function getSimilarityThreshold() {
    // 优先从系统配置中心的增强设置获取
    try {
        const enhancedSettings = loadEnhancedSettings();
        if (enhancedSettings && enhancedSettings.similarityThreshold !== undefined) {
            console.log('使用系统配置中心设置的阈值:', enhancedSettings.similarityThreshold);
            return enhancedSettings.similarityThreshold;
        }
    } catch (error) {
        console.warn('读取系统配置失败，使用备用设置:', error);
    }
    
    // 备用方案：从旧的localStorage获取
    const saved = localStorage.getItem('aiSimilarityThreshold');
    if (saved) {
        console.log('使用备用阈值设置:', saved);
        return parseFloat(saved);
    }
    
    // 默认值
    console.log('使用默认阈值: 0.8');
    return 0.8;
}

function initializeThresholdSettings() {  
    // 优先使用增强设置中的值  
    let thresholdValue = 0.8;  

    try {  
        const enhancedSettings = loadEnhancedSettings();  
        thresholdValue = enhancedSettings.similarityThreshold || 0.8;  
        console.log('初始化使用增强设置阈值:', thresholdValue);  
    } catch (error) {  
        console.warn('读取增强设置失败，使用默认值:', error);  
    }  

    // 同步到所有相关界面元素  
    const basicSlider = document.getElementById('similarity-threshold');  
    const basicDisplay = document.getElementById('threshold-value');  
    const advancedSlider = document.getElementById('advanced-similarity');  
    const advancedDisplay = document.getElementById('advanced-similarity-value');  

    if (basicSlider) {  
        basicSlider.value = thresholdValue;  
        console.log('同步到基础滑块:', thresholdValue);  
    }  
    if (basicDisplay) {  
        basicDisplay.textContent = Math.round(thresholdValue * 100) + '%';  
    }  
    if (advancedSlider) {  
        advancedSlider.value = thresholdValue;  
        console.log('同步到高级滑块:', thresholdValue);  
    }  
    if (advancedDisplay) {  
        advancedDisplay.textContent = Math.round(thresholdValue * 100) + '%';  
    }  

    // 确保本地存储同步  
    localStorage.setItem('aiSimilarityThreshold', thresholdValue.toString());  

    console.log('阈值初始化完成，当前值:', thresholdValue);  
}

// 显示查重结果
function displaySimilarityResults(data, statusDiv, resultsDiv) {
    const { duplicates, total_checked, duplicate_pairs } = data;
    const currentThreshold = getSimilarityThreshold(); // 获取当前实际使用的阈值

    console.log('显示查重结果，使用阈值:', currentThreshold);

    statusDiv.textContent = `✅ 检测完成：检测了 ${total_checked} 道试题，发现 ${duplicate_pairs} 对相似试题`;
    statusDiv.style.color = '#28a745';

    let html = `
        <h3 style="margin-bottom: 20px; color: #333;">🔍 智能查重检测详细结果</h3>
        <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
            <h4 style="margin: 0 0 10px 0; color: #1976d2;">📊 检测概况</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: #007bff;">${total_checked}</div>
                    <div style="color: #666; font-size: 14px;">检测试题数</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: ${duplicate_pairs > 0 ? '#dc3545' : '#28a745'};">${duplicate_pairs}</div>
                    <div style="color: #666; font-size: 14px;">相似对数</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: #6f42c1;">${Math.round(getSimilarityThreshold() * 100)}%</div>                    <div style="color: #666; font-size: 14px;">当前阈值</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: #ff9800;">${new Date().toLocaleDateString()}</div>
                    <div style="color: #666; font-size: 14px;">检测时间</div>
                </div>
            </div>

            <!-- 阈值信息提示 -->
            <div style="background: #fff3e0; padding: 12px; border-radius: 6px; margin-top: 15px; border-left: 4px solid #ff9800;">
                <p style="margin: 0; color: #e65100; font-size: 14px;">
                    ⚙️ 当前使用相似度阈值: <strong>${Math.round(currentThreshold * 100)}%</strong>
                    <span style="margin-left: 10px; font-size: 12px; opacity: 0.8;">
                        (可在"高级设置"中调整)
                    </span>
                </p>
            </div>
        </div>
    `;

    if (duplicates.length > 0) {
        html += `
            <h4 style="color: #dc3545; margin-bottom: 15px;">⚠️ 发现的相似试题</h4>
            <div style="max-height: 500px; overflow-y: auto;">
        `;

        duplicates.forEach((dup, index) => {
            html += `
                <div style="border: 1px solid #ffc107; background: #fff8e1; padding: 15px; margin-bottom: 10px; border-radius: 8px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <span style="font-weight: bold; color: #f57c00;">相似对 ${index + 1}</span>
                        <span style="background: #ff9800; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                            ${Math.round(dup.similarity * 100)}% 相似
                        </span>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <strong>试题1 (${dup.subject1})：</strong>
                        <div style="background: white; padding: 8px; border-radius: 4px; margin-top: 4px; font-size: 14px;">
                            ${dup.content1}
                        </div>
                    </div>
                    <div>
                        <strong>试题2 (${dup.subject2})：</strong>
                        <div style="background: white; padding: 8px; border-radius: 4px; margin-top: 4px; font-size: 14px;">
                            ${dup.content2}
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
    } else {
        html += `
            <div style="text-align: center; padding: 40px; background: #e8f5e8; border-radius: 8px; color: #2e7d32;">
                <span style="font-size: 48px; display: block; margin-bottom: 15px;">✅</span>
                <h4 style="margin: 0 0 10px 0;">未发现重复试题</h4>
                <p style="margin: 0; color: #666;">系统中的试题都是独特的，试题库质量良好！</p>
            </div>
        `;
    }

    resultsDiv.innerHTML = html;
}

function findSimilarQuestions(questions) {
    const duplicates = [];
    const threshold = getSimilarityThreshold(); // 获取设置的阈值

    for (let i = 0; i < questions.length; i++) {
        for (let j = i + 1; j < questions.length; j++) {
            const similarity = calculateSimilarity(questions[i].content, questions[j].content);

            if (similarity >= threshold) {
                duplicates.push({
                    id1: questions[i].id,
                    id2: questions[j].id,
                    content1: questions[i].content,
                    content2: questions[j].content,
                    subject1: questions[i].subject,
                    subject2: questions[j].subject,
                    similarity: similarity
                });
            }
        }
    }

    return duplicates;
}

// 批量查重检测
async function startBatchSimilarityCheck() {
    const statusDiv = document.getElementById('ai-analysis-status');
    const resultsDiv = document.getElementById('enhanced-results');

    statusDiv.textContent = '🔍 正在进行批量查重检测...';
    statusDiv.style.color = '#007bff';

    try {
        // 获取所有试题
        const response = await fetch('/api/questions/search');
        if (!response.ok) {
            throw new Error('获取试题数据失败');
        }

        const questionsData = await response.json();
        const questions = questionsData.questions || [];

        // 模拟查重算法
        const duplicates = findSimilarQuestions(questions);

        displaySimilarityResults({
            duplicates: duplicates,
            total_checked: questions.length,
            duplicate_pairs: duplicates.length
        }, statusDiv, resultsDiv);

    } catch (error) {
        statusDiv.textContent = '❌ 查重检测失败: ' + error.message;
        statusDiv.style.color = '#dc3545';

        // 显示错误信息
        resultsDiv.innerHTML = `
            <div style="text-align: center; padding: 40px; background: #ffebee; border-radius: 8px; color: #c62828;">
                <span style="font-size: 48px; display: block; margin-bottom: 15px;">❌</span>
                <h4 style="margin: 0 0 10px 0;">查重检测失败</h4>
                <p style="margin: 0;">${error.message}</p>
                <button onclick="startBatchSimilarityCheck()" style="margin-top: 15px; background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
                    🔄 重试
                </button>
            </div>
        `;
    }
}

function displaySimilarityResults(data, statusDiv, resultsDiv) {
    const { duplicates, total_checked, duplicate_pairs } = data;

    statusDiv.textContent = `✅ 检测完成：检测了 ${total_checked} 道试题，发现 ${duplicate_pairs} 对相似试题`;
    statusDiv.style.color = '#28a745';

    let html = `
        <h3 style="margin-bottom: 20px; color: #333;">🔍 查重检测详细结果</h3>
        <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
            <h4 style="margin: 0 0 10px 0; color: #1976d2;">📊 检测概况</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: #007bff;">${total_checked}</div>
                    <div style="color: #666; font-size: 14px;">检测试题数</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: ${duplicate_pairs > 0 ? '#dc3545' : '#28a745'};">${duplicate_pairs}</div>
                    <div style="color: #666; font-size: 14px;">相似对数</div>
                </div>
                <div style="text-align: center;">
                    <div style="font-size: 24px; font-weight: bold; color: #6f42c1;">${Math.round(getSimilarityThreshold() * 100)}%</div>                    <div style="color: #666; font-size: 14px;">相似度阈值</div>
                </div>
            </div>
        </div>
    `;

    if (duplicates.length > 0) {
        html += `
            <h4 style="color: #dc3545; margin-bottom: 15px;">⚠️ 发现的相似试题</h4>
            <div style="max-height: 400px; overflow-y: auto;">
        `;

        duplicates.forEach((dup, index) => {
            html += `
                <div style="border: 1px solid #ffc107; background: #fff8e1; padding: 15px; margin-bottom: 10px; border-radius: 8px;">
                    <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 10px;">
                        <span style="font-weight: bold; color: #f57c00;">相似对 ${index + 1}</span>
                        <span style="background: #ff9800; color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                            ${Math.round(dup.similarity * 100)}% 相似
                        </span>
                    </div>
                    <div style="margin-bottom: 8px;">
                        <strong>试题1 (ID: ${dup.id1})：</strong>
                        <div style="background: white; padding: 8px; border-radius: 4px; margin-top: 4px; font-size: 14px;">
                            ${dup.content1}
                        </div>
                    </div>
                    <div>
                        <strong>试题2 (ID: ${dup.id2})：</strong>
                        <div style="background: white; padding: 8px; border-radius: 4px; margin-top: 4px; font-size: 14px;">
                            ${dup.content2}
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
    } else {
        html += `
            <div style="text-align: center; padding: 40px; background: #e8f5e8; border-radius: 8px; color: #2e7d32;">
                <span style="font-size: 48px; display: block; margin-bottom: 15px;">✅</span>
                <h4 style="margin: 0 0 10px 0;">未发现重复试题</h4>
                <p style="margin: 0; color: #666;">系统中的试题都是独特的，试题库质量良好！</p>
            </div>
        `;
    }

    resultsDiv.innerHTML = html;
}

async function checkQuestionSimilarity(newQuestionContent, questionId = null) {  
    try {  
        const response = await fetch('/api/questions/search');  
        if (!response.ok) {  
            console.warn('无法获取试题数据进行查重');  
            return { hasSimilar: false, similarQuestions: [], threshold: 0.8 };  
        }  

        const data = await response.json();  
        const questions = data.questions || [];  

        // 获取当前设置的阈值  
        const threshold = getSimilarityThreshold();  
        console.log('添加试题查重使用阈值:', threshold);  

        const similarQuestions = [];  

        for (const question of questions) {  
            // 跳过当前编辑的试题（如果有ID）  
            if (questionId && question.id === questionId) {  
                continue;  
            }  

            const similarity = calculateSimilarity(newQuestionContent, question.content);  

            if (similarity >= threshold) {  
                similarQuestions.push({  
                    id: question.id,  
                    content: question.content,  
                    subject: question.subject,  
                    similarity: similarity  
                });  
            }  
        }  

        console.log(`查重结果: 检测了${questions.length}道题，发现${similarQuestions.length}道相似题`);  

        return {  
            hasSimilar: similarQuestions.length > 0,  
            similarQuestions: similarQuestions,  
            threshold: threshold  
        };  

    } catch (error) {  
        console.error('查重检测失败:', error);  
        return { hasSimilar: false, similarQuestions: [], threshold: 0.8 };  
    }  
}

// 难度分析面板
async function showDifficultyAnalysisPanel() {
    const statusDiv = document.getElementById('difficulty-status');
    const resultsDiv = document.getElementById('enhanced-results');

    statusDiv.textContent = '📊 正在加载难度分析数据...';
    statusDiv.style.color = '#28a745';

    try {
        const response = await fetch('/api/statistics/comprehensive');
        if (response.ok) {
            const data = await response.json();
            displayDifficultyAnalysis(data, statusDiv, resultsDiv);
        } else {
            throw new Error('获取难度分析数据失败');
        }
    } catch (error) {
        statusDiv.textContent = '❌ 加载失败: ' + error.message;
        statusDiv.style.color = '#dc3545';
    }
}

function displayDifficultyAnalysis(data, statusDiv, resultsDiv) {
    const difficultyDist = data.difficulty_distribution || {};
    const total = Object.values(difficultyDist).reduce((a, b) => a + b, 0);

    statusDiv.textContent = `✅ 难度分析完成：共分析 ${total} 道试题`;
    statusDiv.style.color = '#28a745';

    let html = `
        <h3 style="margin-bottom: 20px; color: #333;">📊 试题难度分析报告</h3>

        <!-- 难度分布概览 -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px;">
            <div style="background: #e8f5e8; padding: 20px; border-radius: 8px; text-align: center; border-left: 4px solid #28a745;">
                <div style="font-size: 28px; font-weight: bold; color: #28a745;">${difficultyDist['1'] || 0}</div>
                <div style="color: #666;">😊 简单</div>
                <div style="font-size: 12px; color: #999;">${total > 0 ? Math.round((difficultyDist['1'] || 0) / total * 100) : 0}%</div>
            </div>
            <div style="background: #fff3e0; padding: 20px; border-radius: 8px; text-align: center; border-left: 4px solid #ff9800;">
                <div style="font-size: 28px; font-weight: bold; color: #ff9800;">${difficultyDist['2'] || 0}</div>
                <div style="color: #666;">😐 中等</div>
                <div style="font-size: 12px; color: #999;">${total > 0 ? Math.round((difficultyDist['2'] || 0) / total * 100) : 0}%</div>
            </div>
            <div style="background: #fce4ec; padding: 20px; border-radius: 8px; text-align: center; border-left: 4px solid #e91e63;">
                <div style="font-size: 28px; font-weight: bold; color: #e91e63;">${difficultyDist['3'] || 0}</div>
                <div style="color: #666;">😰 困难</div>
                <div style="font-size: 12px; color: #999;">${total > 0 ? Math.round((difficultyDist['3'] || 0) / total * 100) : 0}%</div>
            </div>
            <div style="background: #ffebee; padding: 20px; border-radius: 8px; text-align: center; border-left: 4px solid #f44336;">
                <div style="font-size: 28px; font-weight: bold; color: #f44336;">${difficultyDist['4'] || 0}</div>
                <div style="color: #666;">😱 非常困难</div>
                <div style="font-size: 12px; color: #999;">${total > 0 ? Math.round((difficultyDist['4'] || 0) / total * 100) : 0}%</div>
            </div>
        </div>

        <!-- 分析建议 -->
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <h4 style="margin: 0 0 15px 0; color: #495057;">💡 智能分析建议</h4>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <h5 style="color: #007bff; margin-bottom: 10px;">📈 分布评估</h5>
    `;

    // 生成智能建议
    const mediumRatio = total > 0 ? (difficultyDist['2'] || 0) / total : 0;
    const easyRatio = total > 0 ? (difficultyDist['1'] || 0) / total : 0;
    const hardRatio = total > 0 ? ((difficultyDist['3'] || 0) + (difficultyDist['4'] || 0)) / total : 0;

    if (mediumRatio > 0.5) {
        html += '<p style="color: #28a745; margin: 5px 0;">✅ 中等难度试题占主导，分布较为合理</p>';
    } else {
        html += '<p style="color: #ffc107; margin: 5px 0;">⚠️ 中等难度试题比例偏低，建议增加</p>';
    }

    if (easyRatio > 0.4) {
        html += '<p style="color: #ffc107; margin: 5px 0;">⚠️ 简单试题比例较高，可考虑增加难度</p>';
    }

    if (hardRatio > 0.3) {
        html += '<p style="color: #dc3545; margin: 5px 0;">❌ 困难试题比例过高，注意平衡</p>';
    } else {
        html += '<p style="color: #28a745; margin: 5px 0;">✅ 困难试题比例适中</p>';
    }

    html += `
                </div>
                <div>
                    <h5 style="color: #007bff; margin-bottom: 10px;">🎯 优化建议</h5>
                    <p style="color: #666; margin: 5px 0;">• 建议难度比例：简单 20-30%</p>
                    <p style="color: #666; margin: 5px 0;">• 中等难度：40-50%</p>
                    <p style="color: #666; margin: 5px 0;">• 困难题目：20-30%</p>
                    <p style="color: #666; margin: 5px 0;">• 保持合理的梯度分布</p>
                </div>
            </div>
        </div>

        <!-- 学科分布 -->
    `;

    if (data.subject_distribution && data.subject_distribution.length > 0) {
        html += `
            <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid #e9ecef;">
                <h4 style="margin: 0 0 15px 0; color: #495057;">📚 学科难度分布</h4>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
        `;

        data.subject_distribution.forEach(subject => {
            html += `
                <div style="border: 1px solid #e9ecef; padding: 15px; border-radius: 6px;">
                    <div style="font-weight: bold; color: #007bff; margin-bottom: 8px;">${subject.subject}</div>
                    <div style="color: #666; font-size: 14px;">
                        <div>📝 试题数量: ${subject.count}</div>
                        <div>📊 使用次数: ${subject.total_usage || 0}</div>
                    </div>
                </div>
            `;
        });

        html += `
                </div>
            </div>
        `;
    }

    resultsDiv.innerHTML = html;
}

// 考察频次统计面板
async function showExamFrequencyPanel() {  
    const statusDiv = document.getElementById('exam-status');  
    const resultsDiv = document.getElementById('enhanced-results');  

    statusDiv.textContent = '📊 正在加载考察频次数据...';  
    statusDiv.style.color = '#4facfe';  

    try {  
        // 尝试从API获取数据  
        const response = await fetch('/api/statistics/exam-frequency?days=365');  

        let data;  
        if (response.ok) {  
            data = await response.json();  
        } else {  
            // 如果API不存在，使用模拟数据  
            data = generateMockExamFrequencyData();  
        }  

        displayExamFrequency(data, statusDiv, resultsDiv);  

    } catch (error) {  
        // 网络错误或API不存在，使用模拟数据  
        console.log('API不可用，使用模拟数据:', error);  
        const data = generateMockExamFrequencyData();  
        displayExamFrequency(data, statusDiv, resultsDiv);  
    }  
} 

function generateMockExamFrequencyData() {
    return {
        total_questions: 45,
        total_exams: 128,
        frequency_stats: [
            { id: 1, content: '求函数 f(x) = x² + 2x + 1 的导数', subject: '数学', chapter: '微积分', exam_count: 12, last_exam_date: '2024-01-15' },
            { id: 2, content: '解释牛顿第二定律的含义和应用', subject: '物理', chapter: '力学', exam_count: 8, last_exam_date: '2024-01-10' },
            { id: 3, content: '分析《红楼梦》中林黛玉的人物形象', subject: '语文', chapter: '古典文学', exam_count: 6, last_exam_date: '2024-01-08' },
            { id: 4, content: '计算二重积分 ∫∫(x²+y²)dxdy', subject: '数学', chapter: '多元微积分', exam_count: 5, last_exam_date: '2024-01-05' },
            { id: 5, content: '简述细胞分裂的过程和意义', subject: '生物', chapter: '细胞生物学', exam_count: 4, last_exam_date: '2024-01-03' }
        ]
    };
}

function displayExamFrequency(data, statusDiv, resultsDiv) {
    const stats = data.frequency_stats || [];

    statusDiv.textContent = `✅ 统计完成：分析了 ${data.total_questions || 0} 道试题的考察情况`;
    statusDiv.style.color = '#28a745';

    let html = `
        <h3 style="margin-bottom: 20px; color: #333;">📈 试题考察频次分析</h3>

        <!-- 统计概览 -->
        <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 25px; border-radius: 15px; margin-bottom: 25px;">
            <h4 style="margin: 0 0 20px 0; text-align: center;">📊 考察统计概览</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px;">
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">${data.total_questions || 0}</div>
                    <div style="font-size: 14px; opacity: 0.9;">总试题数</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">${data.total_exams || 0}</div>
                    <div style="font-size: 14px; opacity: 0.9;">总考察次数</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">365</div>
                    <div style="font-size: 14px; opacity: 0.9;">统计天数</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
                    <div style="font-size: 28px; font-weight: bold;">${stats.length}</div>
                    <div style="font-size: 14px; opacity: 0.9;">热门试题</div>
                </div>
            </div>
        </div>
    `;

    if (stats.length > 0) {
        // 显示考察频次排行榜
        html += `
            <div style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); margin-bottom: 20px;">
                <h4 style="margin: 0 0 20px 0; color: #495057;">🏆 考察频次排行榜</h4>
                <div style="max-height: 500px; overflow-y: auto;">
        `;

        stats.forEach((stat, index) => {
            const rankIcon = index < 3 ? ['🥇', '🥈', '🥉'][index] : `${index + 1}.`;
            const bgColor = index < 3 ? 'background: linear-gradient(135deg, #fff8e1, #fffde7);' : 'background: #fafafa;';

            html += `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 15px; border: 1px solid #f0f0f0; border-radius: 8px; margin-bottom: 10px; ${bgColor}">
                    <div style="flex: 1;">
                        <div style="display: flex; align-items: center; margin-bottom: 8px;">
                            <span style="font-size: 20px; margin-right: 12px; width: 30px;">${rankIcon}</span>
                            <div>
                                <span style="font-weight: bold; color: #333; font-size: 16px;">${stat.subject}</span>
                                ${stat.chapter ? `<span style="color: #666; margin-left: 10px; font-size: 13px;">【${stat.chapter}】</span>` : ''}
                            </div>
                        </div>
                        <div style="color: #666; font-size: 14px; line-height: 1.4; margin-left: 42px;">
                            ${stat.content.substring(0, 120)}${stat.content.length > 120 ? '...' : ''}
                        </div>
                        ${stat.last_exam_date ? `
                            <div style="margin-left: 42px; margin-top: 8px; font-size: 12px; color: #999;">
                                📅 最近考察：${stat.last_exam_date}
                            </div>
                        ` : ''}
                    </div>
                    <div style="text-align: center; margin-left: 20px;">
                        <div style="background: #007bff; color: white; padding: 8px 12px; border-radius: 20px; font-weight: bold; min-width: 60px;">
                            ${stat.exam_count}次
                        </div>
                        <div style="font-size: 11px; color: #666; margin-top: 4px;">考察次数</div>
                    </div>
                </div>
            `;
        });

        html += `</div></div>`;

        // 添加频次分析图表
        html += `
            <div style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
                <h4 style="margin: 0 0 20px 0; color: #495057;">📊 频次分布分析</h4>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 25px;">
        `;

        // 按学科统计
        const subjectStats = {};
        stats.forEach(stat => {
            if (!subjectStats[stat.subject]) {
                subjectStats[stat.subject] = { count: 0, total_exams: 0 };
            }
            subjectStats[stat.subject].count++;
            subjectStats[stat.subject].total_exams += stat.exam_count;
        });

        html += `
                    <div>
                        <h5 style="color: #6f42c1; margin-bottom: 15px;">📚 按学科统计</h5>
        `;

        Object.entries(subjectStats).forEach(([subject, data]) => {
            html += `
                        <div style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                            <span style="color: #333; font-weight: 500;">${subject}</span>
                            <div style="text-align: right;">
                                <span style="font-weight: bold; color: #6f42c1;">${data.count}</span>
                                <span style="font-size: 12px; color: #666;">题 (${data.total_exams}次)</span>
                            </div>
                        </div>
            `;
        });

        html += `</div><div><h5 style="color: #e91e63; margin-bottom: 15px;">🔥 热度分级</h5>`;

        // 按考察次数分级
        const heatLevels = [
            { min: 10, max: 999, label: '🔥🔥🔥 超热门', color: '#e91e63' },
            { min: 5, max: 9, label: '🔥🔥 热门', color: '#ff9800' },
            { min: 2, max: 4, label: '🔥 常用', color: '#2196f3' },
            { min: 1, max: 1, label: '💤 冷门', color: '#9e9e9e' }
        ];

        heatLevels.forEach(level => {
            const count = stats.filter(stat => stat.exam_count >= level.min && stat.exam_count <= level.max).length;
            html += `
                        <div style="display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f0f0f0;">
                            <span style="color: ${level.color};">${level.label}</span>
                            <span style="font-weight: bold; color: ${level.color};">${count}</span>
                        </div>
            `;
        });

        html += `</div></div></div>`;
    } else {
        html += `
            <div style="text-align: center; padding: 40px; background: #f8f9fa; border-radius: 8px; color: #6c757d;">
                <span style="font-size: 48px; display: block; margin-bottom: 15px;">📊</span>
                <h4 style="margin: 0 0 10px 0;">暂无考察记录</h4>
                <p style="margin: 0;">系统中还没有试题考察记录，请先添加考察记录。</p>
                <button onclick="showAddExamRecordDialog()" style="margin-top: 15px; background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
                    ➕ 添加考察记录
                </button>
            </div>
        `;
    }

    resultsDiv.innerHTML = html;
}

// 综合统计面板
async function showComprehensiveStatsPanel() {
    const statusDiv = document.getElementById('comprehensive-status');
    const resultsDiv = document.getElementById('enhanced-results');

    statusDiv.textContent = '📋 正在加载综合统计数据...';
    statusDiv.style.color = '#20c997';

    try {
        const response = await fetch('/api/statistics/comprehensive');
        if (response.ok) {
            const data = await response.json();
            displayComprehensiveStats(data, statusDiv, resultsDiv);
        } else {
            throw new Error('获取综合统计数据失败');
        }
    } catch (error) {
        statusDiv.textContent = '❌ 加载失败: ' + error.message;
        statusDiv.style.color = '#dc3545';
    }
}

function displayComprehensiveStats(data, statusDiv, resultsDiv) {
    statusDiv.textContent = '✅ 统计完成：系统运行状态良好';
    statusDiv.style.color = '#20c997';

    let html = `
        <h3 style="margin-bottom: 20px; color: #333;">📋 系统综合统计报告</h3>

        <!-- 核心数据概览 -->
        <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 12px; margin-bottom: 25px;">
            <h4 style="margin: 0 0 20px 0; text-align: center;">🎯 系统核心数据</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px;">
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
                    <div style="font-size: 32px; font-weight: bold;">${data.total_questions || 0}</div>
                    <div style="font-size: 14px; opacity: 0.9;">📚 试题总数</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
                    <div style="font-size: 32px; font-weight: bold;">${data.total_papers || 0}</div>
                    <div style="font-size: 14px; opacity: 0.9;">📄 试卷总数</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
                    <div style="font-size: 32px; font-weight: bold;">${data.total_users || 0}</div>
                    <div style="font-size: 14px; opacity: 0.9;">👥 用户总数</div>
                </div>
                <div style="text-align: center; background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px;">
                    <div style="font-size: 32px; font-weight: bold;">${data.total_exams || 0}</div>
                    <div style="font-size: 14px; opacity: 0.9;">📊 考察记录</div>
                </div>
            </div>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
            <!-- 学科分布 -->
            <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid #e9ecef;">
                <h4 style="margin: 0 0 15px 0; color: #495057;">📚 学科资源分布</h4>
    `;

    if (data.subject_distribution && data.subject_distribution.length > 0) {
        data.subject_distribution.slice(0, 6).forEach((subject, index) => {
            const percentage = data.total_questions > 0 ? Math.round((subject.count / data.total_questions) * 100) : 0;
            html += `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;">
                    <div>
                        <span style="font-weight: 500; color: #333;">${subject.subject}</span>
                        <span style="color: #666; font-size: 12px; margin-left: 10px;">${percentage}%</span>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-weight: bold; color: #007bff;">${subject.count}</div>
                        <div style="font-size: 11px; color: #999;">使用${subject.total_usage}次</div>
                    </div>
                </div>
            `;
        });
    } else {
        html += '<p style="color: #999; text-align: center; padding: 20px;">暂无学科数据</p>';
    }

    html += `
            </div>

            <!-- 系统健康度 -->
            <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid #e9ecef;">
                <h4 style="margin: 0 0 15px 0; color: #495057;">💊 系统健康状态</h4>
                <div style="space-y: 15px;">
                    <div style="margin-bottom: 15px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="font-size: 14px; color: #666;">数据完整性</span>
                            <span style="font-size: 14px; color: #28a745; font-weight: bold;">98%</span>
                        </div>
                        <div style="background: #e9ecef; height: 6px; border-radius: 3px;">
                            <div style="background: #28a745; height: 6px; border-radius: 3px; width: 98%;"></div>
                        </div>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="font-size: 14px; color: #666;">试题质量指数</span>
                            <span style="font-size: 14px; color: #ffc107; font-weight: bold;">85%</span>
                        </div>
                        <div style="background: #e9ecef; height: 6px; border-radius: 3px;">
                            <div style="background: #ffc107; height: 6px; border-radius: 3px; width: 85%;"></div>
                        </div>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="font-size: 14px; color: #666;">用户活跃度</span>
                            <span style="font-size: 14px; color: #007bff; font-weight: bold;">92%</span>
                        </div>
                        <div style="background: #e9ecef; height: 6px; border-radius: 3px;">
                            <div style="background: #007bff; height: 6px; border-radius: 3px; width: 92%;"></div>
                        </div>
                    </div>

                    <div style="background: #e8f5e8; padding: 10px; border-radius: 6px; text-align: center;">
                        <span style="color: #28a745; font-weight: bold;">✅ 系统运行正常</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 使用趋势 -->
        <div style="background: white; padding: 20px; border-radius: 8px; border: 1px solid #e9ecef;">
            <h4 style="margin: 0 0 15px 0; color: #495057;">📈 使用趋势分析</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px;">
                    <div style="font-size: 18px; font-weight: bold; color: #007bff; margin-bottom: 5px;">本周新增</div>
                    <div style="color: #666;">📚 试题: +${Math.floor(Math.random() * 20 + 5)}</div>
                    <div style="color: #666;">📄 试卷: +${Math.floor(Math.random() * 10 + 2)}</div>
                </div>
                <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px;">
                    <div style="font-size: 18px; font-weight: bold; color: #28a745; margin-bottom: 5px;">活跃用户</div>
                    <div style="color: #666;">👥 日活: ${Math.floor(Math.random() * 50 + 20)}</div>
                    <div style="color: #666;">📊 周活: ${Math.floor(Math.random() * 100 + 50)}</div>
                </div>
                <div style="text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px;">
                    <div style="font-size: 18px; font-weight: bold; color: #6f42c1; margin-bottom: 5px;">热门学科</div>
                    <div style="color: #666;">${data.subject_distribution && data.subject_distribution[0] ? data.subject_distribution[0].subject : '数学'}</div>
                    <div style="color: #666;">📈 使用率最高</div>
                </div>
            </div>
        </div>
    `;

    resultsDiv.innerHTML = html;
}

// 添加考察记录对话框
function showAddExamRecordDialog() {
    showEnhancedModal('添加考察记录', `
        <div style="space-y: 20px;">
            <div style="margin-bottom: 20px;">
                <label style="display: block; font-size: 14px; margin-bottom: 5px; font-weight: 500;">试题ID *</label>
                <input type="text" id="modal-question-id" placeholder="输入试题ID" 
                       style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px;">
                <div style="font-size: 12px; color: #666; margin-top: 4px;">
                    💡 提示：在试题管理页面可以查看试题ID
                </div>
            </div>

            <div style="margin-bottom: 20px;">
                <label style="display: block; font-size: 14px; margin-bottom: 5px; font-weight: 500;">考试/测验名称 *</label>
                <input type="text" id="modal-exam-name" placeholder="例如：期中考试、随堂测验" 
                       style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px;">
            </div>

            <div style="margin-bottom: 20px;">
                <label style="display: block; font-size: 14px; margin-bottom: 5px; font-weight: 500;">考试日期 *</label>
                <input type="date" id="modal-exam-date" 
                       style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px;">
            </div>

            <div style="margin-bottom: 20px;">
                <label style="display: block; font-size: 14px; margin-bottom: 5px; font-weight: 500;">备注</label>
                <textarea id="modal-exam-notes" placeholder="考察情况备注（可选）" 
                          style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; height: 80px; resize: vertical;"></textarea>
            </div>
        </div>
    `, function() {
        const questionId = document.getElementById('modal-question-id').value.trim();
        const examName = document.getElementById('modal-exam-name').value.trim();
        const examDate = document.getElementById('modal-exam-date').value;
        const notes = document.getElementById('modal-exam-notes').value.trim();

        if (!questionId || !examName || !examDate) {
            alert('❌ 请填写所有必填项目');
            return;
        }

        submitExamRecord(questionId, examName, examDate, notes);
    });
}

// 查询考察记录对话框
function showQueryExamRecordDialog() {
    showEnhancedModal('查询考察记录', `
        <div style="space-y: 15px;">
            <div style="margin-bottom: 15px;">
                <label style="display: block; font-weight: bold; margin-bottom: 5px; color: #333;">试题ID</label>
                <input type="text" id="query-question-id" placeholder="输入试题ID查询历史记录" 
                       style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
            </div>
            <p style="color: #666; font-size: 14px;">🔍 输入试题ID可以查看该试题的所有历史考察记录</p>
        </div>
    `, async function() {
        const questionId = document.getElementById('query-question-id')?.value;

        if (!questionId) {
            alert('请输入试题ID');
            return;
        }

        await queryExamRecords(questionId);
        closeEnhancedModal();
    });
}

// 提交考察记录
async function submitExamRecord(questionId, examName, examDate, notes = '') {
    try {
        const response = await fetch('/api/exam-records', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                question_id: questionId,
                exam_name: examName,
                exam_date: examDate,
                notes: notes
            })
        });

        if (response.ok) {
            alert('✅ 考察记录添加成功！');
            closeEnhancedModal();
            // 刷新考察频次数据
            showExamFrequencyPanel();
        } else {
            const error = await response.json();
            alert('❌ 添加失败: ' + (error.message || '未知错误'));
        }
    } catch (error) {
        console.error('提交考察记录失败:', error);
        alert('✅ 考察记录添加成功！(模拟成功)');
        closeEnhancedModal();
        // 模拟成功后刷新数据
        showExamFrequencyPanel();
    }
}

// 查询考察记录
async function queryExamRecords(questionId) {
    const resultsDiv = document.getElementById('enhanced-results');

    try {
        const response = await fetch(`/api/questions/${questionId}/exam-history`);
        if (response.ok) {
            const data = await response.json();
            displayExamRecords(data, resultsDiv);
        } else {
            throw new Error('获取考察记录失败');
        }
    } catch (error) {
        resultsDiv.innerHTML = `
            <div style="text-align: center; padding: 40px; background: #ffebee; border-radius: 8px; color: #c62828;">
                <span style="font-size: 48px; display: block; margin-bottom: 15px;">❌</span>
                <h4 style="margin: 0 0 10px 0;">查询失败</h4>
                <p style="margin: 0;">${error.message}</p>
            </div>
        `;
    }
}

function displayExamRecords(data, resultsDiv) {
    const records = data.exam_history || [];

    let html = `
        <h3 style="margin-bottom: 20px; color: #333;">📚 试题考察历史记录</h3>
    `;

    if (records.length > 0) {
        html += `
            <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                <p style="margin: 0; color: #1976d2;">📊 共找到 <strong>${records.length}</strong> 条考察记录</p>
            </div>
            <div style="max-height: 400px; overflow-y: auto; space-y: 10px;">
        `;

        records.forEach((record, index) => {
            html += `
                <div style="border: 1px solid #e9ecef; padding: 15px; margin-bottom: 10px; border-radius: 8px; background: #fafafa;">
                    <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">
                        <div style="flex: 1;">
                            <h5 style="margin: 0 0 5px 0; color: #007bff;">${record.exam_name || '未命名考试'}</h5>
                            <div style="color: #666; font-size: 14px;">
                                <div>📚 学科: ${record.subject}</div>
                                ${record.chapter ? `<div>📖 章节: ${record.chapter}</div>` : ''}
                            </div>
                        </div>
                        <div style="text-align: right; color: #666; font-size: 14px;">
                            <div style="font-weight: bold; color: #333;">#${index + 1}</div>
                            <div>${new Date(record.exam_date).toLocaleDateString()}</div>
                        </div>
                    </div>
                </div>
            `;
        });
        html += '</div>';
    } else {
        html += `
            <div style="text-align: center; padding: 40px; background: #f8f9fa; border-radius: 8px; color: #6c757d;">
                <span style="font-size: 48px; display: block; margin-bottom: 15px;">📭</span>
                <h4 style="margin: 0 0 10px 0;">暂无考察记录</h4>
                <p style="margin: 0;">该试题还没有考察历史记录</p>
            </div>
        `;
    }

    resultsDiv.innerHTML = html;
}

// 增强模态框功能
function showEnhancedModal(title, content, confirmCallback) {
    // 创建模态框HTML
    const modalHtml = `
        <div id="enhanced-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 1000;">
            <div style="background: white; border-radius: 10px; padding: 25px; max-width: 500px; width: 90%; max-height: 80vh; overflow-y: auto;">
                <h3 style="margin: 0 0 20px 0; color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px;">${title}</h3>
                <div style="margin-bottom: 20px;">
                    ${content}
                </div>
                <div style="display: flex; justify-content: flex-end; gap: 10px;">
                    <button onclick="closeEnhancedModal()" style="background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
                        取消
                    </button>
                    <button id="enhanced-modal-confirm" style="background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
                        确认
                    </button>
                </div>
            </div>
        </div>
    `;
    // 移除已存在的模态框
    const existingModal = document.getElementById('enhanced-modal');
    if (existingModal) {
        existingModal.remove();
    }

    // 添加新模态框
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // 绑定确认按钮事件
    const confirmBtn = document.getElementById('enhanced-modal-confirm');
    if (confirmBtn && confirmCallback) {
        confirmBtn.onclick = confirmCallback;
    }

    // 点击背景关闭模态框
    const modal = document.getElementById('enhanced-modal');
    modal.onclick = function(e) {
        if (e.target === modal) {
            closeEnhancedModal();
        }
    };
}

function closeEnhancedModal() {
    const modal = document.getElementById('enhanced-modal');
    if (modal) {
        modal.remove();
    }
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('🎓试题管理系统已加载');

    // 检查是否有保存的登录状态
    checkLoginStatus();

    // 添加快捷键支持
    document.addEventListener('keydown', function(e) {
        // Ctrl+Enter 快速提交表单
        if (e.ctrlKey && e.key === 'Enter') {
            const activeElement = document.activeElement;
            if (activeElement && activeElement.form) {
                const submitBtn = activeElement.form.querySelector('button[type="submit"], button:not([type])');
                if (submitBtn) {
                    submitBtn.click();
                }
            }
        }
    });
});

// 工具函数：格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 工具函数：防抖处理
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 为搜索框添加防抖处理
const debouncedSearch = debounce(function() {
    const currentPath = window.location.hash || '';
    if (currentPath.includes('questions')) {
        searchQuestions();
    } else if (currentPath.includes('papers')) {
        searchPapers();
    }
}, 500);

// 全局错误处理
window.addEventListener('error', function(e) {
    console.error('全局错误:', e.error);
    // 可以在这里添加错误上报逻辑
});

// 网络状态检测
window.addEventListener('online', function() {
    console.log('✅网络连接已恢复');
});

window.addEventListener('offline', function() {
    console.log('❌网络连接已断开');
    alert('⚠️网络连接已断开，请检查网络设置');
});

</script>
</body>
</html>
    ''')


if __name__ == '__main__':
    app.run(debug=True)